在javascript中制作类函数的正确方法

时间:2012-08-28 10:16:42

标签: javascript class methods

我有以下代码:

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

new Class().method();

它工作正常,但据我所知,每个新对象都将创建该函数。有没有正确的方法呢?

2 个答案:

答案 0 :(得分:5)

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

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

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

new Class('var1', 'var2').method();
​

答案 1 :(得分: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;
    }
});