2

我有以下代码:

function Class () {
  this.method = function () {
    alert('method');
  };
}

new Class().method();

它工作正常,但据我了解,将为每个新对象创建该函数。有正确的方法吗?

​</p>

4

2 回答 2

5

将实例变量的初始化放在 Class 函数中,并将共享方法和变量放在原型属性中:

function Class (var1, var2) {
  this.var1 = var1;
  this.var2 = var2;
}

Class.prototype.method = function () {
  alert(this.var1 + ' ' + this.var2);
};

new Class('var1', 'var2').method();
​
于 2012-08-28T10:17:21.870 回答
0

我的方法与 Speransky 的方法几乎相同,但我重新声明了原型对象,而不是直接向它添加方法。

// Declare the Constructor function.
function MyClass (name, age) {

    // Assign any member properties here.
    this._name = name;
    this.age = age;
}

// Redefine the prototype object to add methods.
MyClass.prototype = {

    // Re-point the Constructor function as it will be overwritten.
    constructor: MyClass,

    // Custom method which all instances of `MyClass` will inherit.
    sayHello: function () { 
        return "My name is " + this._name + ", how do you do?";
    }
};

用法:

var foo = new MyClass("Dave", 22);
foo.sayHello();     // "My name is Dave, how do you do?"
foo.age;            // 22

如果你想将MyClass原型指向另一个对象(设置一个简单的继承模型),那么你可以使用一个 mixin,类似于 Underscore 的extend方法:

function BaseClass(name) {
    this._name = name;
}

BaseClass.prototype = {
    constructor: BaseClass,

    sayHello: function () { 
        return "My name is " + this._name + ", how do you do?";
    }
}

class MyClass (name, age) {
    // Call the BaseClass constructor function in the context of `this`
    BaseClass.call(this, name);

    this.age = age;
}

// Mixin the BaseClass's protptype into the MyClass prototype and delcare
// the new methods.
_.extend(MyClass.Prototype, BaseClass.prototype, {
    constructor: MyClass,

    getAge: function () { 
        return this.age;
    }
});
于 2012-08-28T10:27:08.123 回答