Animal.prototype.sayHello = function () { console.log("Hello, my species is Animal."); };
functionCat(name) { this.name = name; }
// 将父类的实例作为子类的原型 Cat.prototype = new Animal();
let cat1 = new Cat("Tom"); console.log(cat1.species); // Animal console.log(cat1.name); // Tom console.log(cat1.color); // ["black", "white"] cat1.sayHello(); // Hello, my species is Animal.
let cat2 = new Cat("Jack"); cat2.color.push("blue");
let cat1 = new Cat("Tom"); console.log(cat1.species); // Cat console.log(cat1.name); // Tom console.log(cat1.color); // ["black", "white"] cat1.sayHello(); // Uncaught TypeError: cat1.sayHello is not a function
let cat2 = new Cat("Jack"); cat2.color.push("blue"); console.log(cat2.color); // ["black", "white", "blue"] console.log(cat1.color); // ["black", "white"]
Animal.prototype.sayHello = function () { console.log(`Hello, my species is ${this.species}.`); };
functionCat(name) { let animal = new Animal("Cat"); animal.name = "Tom"; return animal; }
let cat1 = new Cat("Tom"); console.log(cat1.species); // Cat console.log(cat1.name); // Tom console.log(cat1.color); // ["black", "white"] cat1.sayHello(); // Hello, my species is Cat.
let cat2 = new Cat("Jack"); cat2.color.push("blue"); console.log(cat2.color); // ["black", "white", "blue"] console.log(cat1.color); // ["black", "white"]
Animal.prototype.sayHello = function () { console.log(`Hello, my species is ${this.species}.`); };
functionCat(name) { let f = new Animal("Cat"); for (let k in f) { Cat.prototype[k] = f[k]; } Cat.prototype.name = name; }
let cat1 = new Cat("Tom"); console.log(cat1.species); // Cat console.log(cat1.name); // Tom console.log(cat1.color); // ["black", "white"] cat1.sayHello(); // Hello, my species is Cat.
let cat2 = new Cat("Jack"); cat2.color.push("blue"); console.log(cat2.color); // ["black", "white", "blue"] console.log(cat1.color); // ["black", "white", "blue"]