面试必问之继承

22次阅读

共计 1061 个字符,预计需要花费 3 分钟才能阅读完成。

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);

正文完
 0