js 原型式继承注意事项

时间:2022-10-16 22:40:57
1.Person父类

var Person = {
name:"default name",
getName: function () {
return this.name;
}
};

2.Author是Person的子类

var Author = clone(Person);
Author.books = [];
Author.getBooks = function () {
return this.books;
};

3.authorClone是Author子类

var authorClone = clone(Author);
console.log("authorCloneName:"+ authorClone.name);

//执行完此,父类Peroson和Author中的name为"default name",而authorClone子类的name='new name'
authorClone.name = 'new name';
console.log("authorCloneName:"+ authorClone.name);

//执行完此,Author父类中的books='new book',authorClone子类books='new book'
authorClone.books.push('new book');

//执行完此,Author父类中的books还是原来的,
//authorClone.books = 'new book';
authorClone.books = [];
authorClone.books.push('new book1');

注意:用push导致结果不一样的原因是,由于books是数组类型,直接使用push()是 引用 的方式修改,所有父类的值也会改变; 但是用 "=" 号的形式是修改了引用地址,所有父类的books不会受影响