FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

使用原型链如何实现继承

Open lgwebdream opened this issue 4 years ago • 2 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

function animal() {
    this.name = 'animal';
    this.colors = ['red', 'blue', 'green'];
}

animal.prototype.getName = function() {
    return this.name;
}

function dog() {
}

dog.prototype = new animal();

const dog1 = new dog();
console.log('dog1.name:', dog1.getName()); // animal
console.log('dog1.colors:', dog1.colors); // ['red', 'blue', 'green']

dog1.name = 'dog';
dog1.colors.push('black'); // 引用类型的值会共享
const dog2 = new dog();
console.log('dog2.name:', dog2.getName()); // animal
console.log('dog2.colors:', dog2.colors); // ['red', 'blue', 'green', 'black']

rubickecho avatar Jan 11 '22 14:01 rubickecho