js继承经常使用的三种方法,记录一下,立刻要面试了。面试
以为有用能够帮我点个赞吗?谢谢了。函数
// 原型链继承 function Parent() { this.name = '原型链继承'; this.play = [1,2,3]; } Parent.prototype.getName = function () { console.log(this.name); } function Child() { this.type = '原型链继承child'; } Child.prototype = new Parent(); // 原型链上的原型对象是通用的,改变一个,其余的都会改变,但咱们不想全部对象都改变 var child1 = new Child(); var child2 = new Child(); child1.play.push(4) console.log(child1.play) console.log(child2.play)
// 构造函数继承 function Parent() { this.name = '构造函数继承'; this.play = [1,2,3]; } Parent.prototype.getName = function () { console.log(this.name); } function Child() { Parent.call(this) this.type = '构造函数继承child'; } var child1 = new Child(); console.log(child1.getName) //构造函数继承不会继承原型链上的方法
// 组合继承 // 原理:建立中间对象,中间对象的原型对象是父类的 function Parent() { this.name = '组合继承'; this.play = [1,2,3]; } Parent.prototype.getName = function () { console.log(this.name); } function Child() { Parent.call(this) this.type = '组合继承child'; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; //没有这句代码,Child.prototype.constructor会指向Parent var child = new Child() console.log(child instanceof Child,child instanceof Parent); console.log(child.constructor);