向Javascript对象添加函数的不同方法 [英] Different ways to add functions to Javascript object

查看:83
本文介绍了向Javascript对象添加函数的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,这两种向对象添加函数的方法有什么区别吗?出于任何原因,一个人更好吗?

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

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

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


推荐答案

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

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 AlertA to the prototype of the ObjA constructor, 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 in:

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

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

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

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!

这篇关于向Javascript对象添加函数的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆