简体   繁体   English

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

[英]The difference between the method defined using the following two

Snippet1: Snippet1:

 var box = function() {};

 box.prototype.open = function {
 };

Snippet2: Snippet2:

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

Any difference between those two, which one is better? 这两者之间有什么区别,哪一个更好?

Shall we assume that box is a constructor, so you're doing new box() ? 我们应该假设box是一个构造函数,所以你正在做new box()

If so... 如果是这样的话...

  • The first version will share the open function among all objects created from the box constructor. 第一个版本将在从box构造函数创建的所有对象之间共享open函数。

  • The second will generate a new function object for every object created from the box constructor. 第二个将为从box构造函数创建的每个对象生成一个新的函数对象。

As such, the first will be more memory efficient than the second. 因此,第一个将比第二个更有效。


First version: 第一版:

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

Second version: 第二版:

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

@am not i am is correct. @am不是我是对的。 First method is the efficient way to do it. 第一种方法是有效的方法。 Second method is useful if you need private variables. 如果您需要私有变量,第二种方法很有用。

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 
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM