有什么区别
var A = function () {
this.x = function () {
//do something
};
};
Run Code Online (Sandbox Code Playgroud)
和
var A = function () { };
A.prototype.x = function () {
//do something
};
Run Code Online (Sandbox Code Playgroud) 所以我有这两个例子,来自javascript.info:
例1:
var animal = {
eat: function() {
alert( "I'm full" )
this.full = true
}
}
var rabbit = {
jump: function() { /* something */ }
}
rabbit.__proto__ = animal
rabbit.eat()
Run Code Online (Sandbox Code Playgroud)
例2:
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)
从示例2开始:当代码到达时 …
我一直在想JavaScript的原型性质及其好处,并且归结为以下列表:
1)继承
cat.prototype = animal
Run Code Online (Sandbox Code Playgroud)
2)内存效率
a.prototype.b = function() {}
var a1 = new a();
var a2 = new a();
Run Code Online (Sandbox Code Playgroud)
那么a1.b和a2.b本质上是同一个对象,其中:
var a = function() {
this.b = function() {};
}
var a1 = new a();
var a2 = new a();
Run Code Online (Sandbox Code Playgroud)
a1.b和a2.b将是不同的函数对象并占用更多内存.
3)将方法/字段添加到已经创建的多个"野外"对象中.
var a = function() {}
var a1 = new a();
var a2 = new a();
a.prototype.b = function() {}
a1.b();
a2.b();
Run Code Online (Sandbox Code Playgroud)
所以问题是,这些是正确的吗?
......还有其他任何我错过的好处吗?
干杯!