向 Javascript 对象添加函数的不同方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7109966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:53:08  来源:igfitidea点击:

Different ways to add functions to Javascript object

javascript

提问by Adam Rackis

In Javascript is there any difference between these two ways of adding a function to an object? Is one preferable for any reason?

在Javascript中,这两种向对象添加函数的方式有什么区别吗?出于某种原因是可取的吗?

function ObjA() {
    this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };

var A = new ObjA();
A.AlertA();
A.AlertB();

回答by KooiInc

Sure there is a difference. If you define this.AlertA, you are defining a method that is local for the instance of ObjA. If you add AlertAto the prototype of the ObjAconstructor, it is defined for every instance of ObjA. The latter is, in this case, more efficient, because it's only assigned once, whilst a local method is assigned every time you create an instance of ObjA.

当然有区别。如果您定义this.AlertA,则您正在为 的实例定义本地方法ObjA。如果添加AlertAObjA构造函数的原型中,则它是为 的每个实例定义的ObjA。在这种情况下,后者更有效,因为它只分配一次,而每次创建ObjA.

So using this.AlertAin:

所以用this.AlertA在:

var A = new ObjA, 
    B = new ObjA,
    C = new ObjA;

for A, B and C the constructor has to add the method AlertA. AlertBon the other hand, is only added once. You can check that using:

对于 A、B 和 C,构造函数必须添加方法AlertAAlertB另一方面,只添加一次。您可以使用以下方法检查:

function ObjA() {
        alert('adding AlertA!');
        this.AlertA = function() { 
            alert("A"); 
        };

        if (!ObjA.prototype.AlertB) {
            alert('adding AlertB!');
            ObjA.prototype.AlertB = function() { 
                alert("B"); 
            };
        }
}

var A = new ObjA,  //=>  alerts adding AlertA! and alerts adding AlertB!
    B = new ObjA,  //=>  alerts adding AlertA!
    C = new ObjA;  //=>  alerts adding AlertA!

回答by heisenberg

Using the object constructor will assign a copy of that function to every new instance of your object. Using prototyping will result in one function being shared across all instances.

使用对象构造函数将为对象的每个新实例分配该函数的副本。使用原型设计将导致所有实例共享一个功能。