你能解释一下为什么有必要(或推荐)在JavaScript继承中使用“__proto__”和“prototype”吗?这里有两个代码示例,它们的结果似乎与使用和不使用原型完全相同。在两种情况下结果如下:
“大象正走向墨尔本”
“麻雀正走向悉尼”
“麻雀飞向墨尔本”示例一:
function Animal(name) {
this.name = name;
}
Animal.prototype.walk = function (destination) {
console.log(this.name, 'is walking to', destination);
};
var animal = new Animal('elephant');
animal.walk('melbourne');
function Bird(name) {
Animal.call(this, name);
}
Bird.prototype.__proto__ = Animal.prototype;
Bird.prototype.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
var bird = new Bird('sparrow');
bird.walk('sydney');
bird.fly('melbourne');
示例二:
function Animal(name) {
this.name = name;
this.walk = function (destination) {
console.log(this.name, 'is walking to', destination);
};
}
var animal = new Animal('elephant');
animal.walk('melbourne');
function Bird(name) {
Animal.call(this, name);
this.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
}
var bird = new Bird('sparrow');
bird.walk('sydney');
bird.fly('melbourne');
例如为什么“Bird.prototype.fly = function ...”比Bird函数中的简单“this.fly = function ...”更好?
答案 0 :(得分:1)
我认为这应该足够明确。我把动物带出了剧本(呃......字面意思)。
function Bird(name) {
this.name = name;
this.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
}
var bird = new Bird('sparrow');
bird.fly('Melbourne');
bird.fly = function (destination) {
console.log(this.name, 'is taking the plane to', destination);
}
bird.fly('Melbourne');
var bird2 = new Bird('eagle');
bird2.fly('Melbourne');
给出了
麻雀飞往墨尔本 麻雀正乘飞机前往墨尔本 老鹰飞往墨尔本
VS
function Bird(name) {
this.name = name;
}
Bird.prototype.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
var bird = new Bird('sparrow');
bird.fly('Melbourne');
Bird.prototype.fly = function (destination) {
console.log(this.name, 'is taking the plane to', destination);
}
bird.fly('Melbourne');
var bird2 = new Bird('eagle');
bird2.fly('Melbourne');
给出了
麻雀飞往墨尔本 麻雀正乘飞机前往墨尔本 鹰正乘飞机前往墨尔本
在第一种情况下,您正在修改该对象的fly函数。在第二种情况下,您正在修改一个共同的共享函数(来自原型)
由于你最希望函数是通用的(并且数据是分开的),你通常使用Bird.prototype ....