javascript之间创建对象有什么区别
test = function(a, b){
this.calculate = function(){
return a + b;
}
}
obj = new test(1, 2);
console.log(obj.calculate());
和
test = function(a, b){
return {
calculate: function(){
return a + b;
}
}
}
obj = test(1, 2);
console.log(obj.calculate());
我在不同的情况下都使用过这两种方法,但从未理解过它们之间的区别,我知道后一种方法具有为实例创建函数的开销,但仍然看到它在很多情况下都被使用过,谁能为我澄清一下?我无法通过搜索找到任何相关信息
最佳答案
第一个还为每个实例创建函数。这种情况的唯一区别是第一种情况下新实例继承自test.prototype
,而第二种情况下它直接继承自Object
。
在第一种情况下,通过将函数添加到原型(prototype),让实例共享代码会更容易。例如:
var Test = function(a, b){
this._a = a;
this._b = b;
};
Test.prototype.calculate = function(){
return this._a + this._b;
};
由于所有实例都继承自 Test.prototype
,calculate
函数只存在一次,所有实例都引用同一个函数。
关于Javascript 对象实例与返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14475909/