6

在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());

我在不同的情况下都使用过这两种方法,但从来不理解它们的区别,我知道后一种方法有为永远创建函数的开销,但仍然看到它在很多情况下使用,有人可以为我澄清一下吗?我无法通过搜索找到有关此的任何信息

4

2 回答 2

5

第一个还为每个实例创建函数。这种情况的唯一区别是新实例test.prototype在第一种情况下继承自,而Object在第二种情况下直接继承自。

在第一种情况下,通过将函数添加到原型中,让实例共享代码会更容易。例如:

var Test = function(a, b){
   this._a = a;
   this._b = b;
};

Test.prototype.calculate = function(){
   return this._a + this._b;
};

Since all instances inherit from Test.prototype, the calculate function exists only once and all instances refer to the same function.

于 2013-01-23T09:18:50.320 回答
2

As Felix said in the comment, the difference is the inheritance chain. The first inherits from test.prototype and the second from Object. The consequence is that if you wanted to create the function only once and make every instance share it, you'd have to do something like this:

test = function (a, b) {
  this.a = a;
  this.b = b;
}

test.prototype.calculate = function () {
  return this.a + this.b;
}
于 2013-01-23T09:18:57.340 回答