使用以下两种方法定义的方法之间的区别

时间:2012-01-15 07:02:52

标签: javascript

Snippet1:

 var box = function() {};

 box.prototype.open = function {
 };

Snippet2:

  var box = function() {
      this.open = function() {
      };
  }

这两者之间有什么区别,哪一个更好?

2 个答案:

答案 0 :(得分:5)

我们假设box是构造函数,所以你正在做new box()吗?

如果是这样......

  • 第一个版本将在open构造函数创建的所有对象中共享box函数。

  • 第二个将为从box构造函数创建的每个对象生成一个新的函数对象。

因此,第一个将比第二个更有效。


第一版:

    new box                 box prototype            object prototype
+--------------+          +--------------+          +--------------+
|              |          |              |          |              |
|              |--------->|  open func   |--------->|              |
|              |       /  |              |          |              |
+______________+      /   +______________+          +______________+
                     /
                    /
    new box        /
+--------------+  /
|              | /
|              |/
|              |
+______________+

第二版:

    new box                box prototype            object prototype
+--------------+          +--------------+          +--------------+
|              |          |              |          |              |
|  open func   |--------->|              |--------->|              |
|              |       /  |              |          |              |
+______________+      /   +______________+          +______________+
                     /
                    /
    new box        /
+--------------+  /
|              | /
|  open func   |/
|              |
+______________+

答案 1 :(得分:5)

@am不是我是对的。第一种方法是有效的方法。 如果您需要私有变量,第二种方法很有用。

var box = function() {
     var _message = "hello world";
     this.func2 = function(){
       console.log(_message);   // prints hello world
     }
};

box.prototype.func1 = function() {
     this.func2();              // prints hello world
     console.log(_message);     // throws ReferenceError: _message is not defined 
};