JavaScript 对象中的构造函数

2022-08-29 23:27:02

JavaScript类/对象可以有构造函数吗?它们是如何创建的?


答案 1

使用原型:

function Box(color) // Constructor
{
    this.color = color;
}

Box.prototype.getColor = function()
{
    return this.color;
};

隐藏“颜色”(有点类似于私有成员变量):

function Box(col)
{
   var color = col;

   this.getColor = function()
   {
       return color;
   };
}

用法:

var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue

var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green

答案 2

这是我有时在JavaScript中用于OOP类似行为的模板。如您所见,您可以使用闭包模拟私有(静态和实例)成员。将返回的是一个对象,该对象仅具有分配给该对象的属性以及“类”的对象。new MyClass()thisprototype

var MyClass = (function () {
    // private static
    var nextId = 1;

    // constructor
    var cls = function () {
        // private
        var id = nextId++;
        var name = 'Unknown';

        // public (this instance only)
        this.get_id = function () { return id; };

        this.get_name = function () { return name; };
        this.set_name = function (value) {
            if (typeof value != 'string')
                throw 'Name must be a string';
            if (value.length < 2 || value.length > 20)
                throw 'Name must be 2-20 characters long.';
            name = value;
        };
    };

    // public static
    cls.get_nextId = function () {
        return nextId;
    };

    // public (shared across instances)
    cls.prototype = {
        announce: function () {
            alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
                  'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
        }
    };

    return cls;
})();

我被问及使用此模式进行继承,所以这里是:

// It's a good idea to have a utility class to wire up inheritance.
function inherit(cls, superCls) {
    // We use an intermediary empty constructor to create an
    // inheritance chain, because using the super class' constructor
    // might have side effects.
    var construct = function () {};
    construct.prototype = superCls.prototype;
    cls.prototype = new construct;
    cls.prototype.constructor = cls;
    cls.super = superCls;
}

var MyChildClass = (function () {
    // constructor
    var cls = function (surName) {
        // Call super constructor on this instance (any arguments
        // to the constructor would go after "this" in call(…)).
        this.constructor.super.call(this);

        // Shadowing instance properties is a little bit less
        // intuitive, but can be done:
        var getName = this.get_name;

        // public (this instance only)
        this.get_name = function () {
            return getName.call(this) + ' ' + surName;
        };
    };
    inherit(cls, MyClass); // <-- important!

    return cls;
})();

举个例子来说明这一切:

var bob = new MyClass();
bob.set_name('Bob');
bob.announce(); // id is 1, name shows as "Bob"

var john = new MyChildClass('Doe');
john.set_name('John');
john.announce(); // id is 2, name shows as "John Doe"

alert(john instanceof MyClass); // true

如您所见,这些类正确地相互交互(它们共享来自 的静态 ID,该方法使用正确的方法等)。MyClassannounceget_name

需要注意的一点是需要影子实例属性。您实际上可以使函数遍历作为函数的所有实例属性(使用),并自动添加属性。这将允许您调用,而不是将其存储在临时值中并使用 调用绑定。inherithasOwnPropertysuper_<method name>this.super_get_name()call

对于原型上的方法,您不必担心上述问题,但是,如果要访问超类的原型方法,只需调用 。如果你想让它不那么冗长,你当然可以添加便利属性。:)this.constructor.super.prototype.methodName