如何将方法添加到对象的实例

时间:2013-08-13 11:25:09

标签: javascript

例如,我有一个对象的实例:

A = function(){};
a = new A();

如何添加方法

{b: function(){ console.log('b') },
 c: function(){ console.log('c') }
}

以实例a?

4 个答案:

答案 0 :(得分:2)

你应该看看prototype

Here是一个很好的解释。

编辑:您还可以将原型设置为一系列函数,例如:

var Person = new function() {};

methods = {
    "methodA": function() {alert("method A")},
    "methodB": function() {alert("method B")},                         
}

Person.prototype = methods

p = new Person()
p.methodA(); // Alerts "method A"

答案 1 :(得分:2)

如果要向实例添加方法,只需添加它们:

a.methodA = function() {
    alert("method A");
};

您可以使用任何对象执行此操作。但是,您也可以将它们添加到实例的原型中,这将允许在所有其他实例上显示相同的方法:

var a = new A(),
    b = new A();

a.prototype.methodA = function() {
    alert("method A");
};

b.methodA();

如果要一次添加多个方法,请创建混合函数或使用框架:

function mix(a, b, typ) {
    var n, o;

    for (n in b) {
        if (! b.hasOwnProperty(n)) continue;

        if (!!(o = b[[n]) && (! typ || typeof o === typ)) {
            a[n] = o;
        }
    }
}

则...

var a = new A();

mix(a, {
    "methodA": function() {
        alert("method A");
    },
    "methodB": function() {
        alert("method B");
    }
}, "function");

答案 2 :(得分:0)

Prototype用于向特定类型对象的所有实例添加方法(对内存管理很有用)。如果您只想将方法添加到对象的一个​​实例,则可以像添加任何属性一样添加它们:

var A = function() {
    //......
}

var myA = new A();
myA.methodOne = function() { console.log('called methodOne on myA'); }
myA.methodTwo = function() { console.log('called methodTwo on myA'); }

myA.methodOne();
myA.methodTwo();

答案 3 :(得分:0)

如果您对使用库/框架感到满意,请查看jQuery.extend()

A = function(){};
a = new A();
d = {b: function(){ console.log('b') },
     c: function(){ console.log('c') }
    };
$.extend(a, d);
相关问题