0
var Foo = (function () {

    var cls = function () {
        this.prototype = {
            sayhi: function () {
                alert('hi');
            }
        };
    };

    cls.staticMethod = function () {};

    return cls;

})();

var f = new Foo();

为什么我无法访问我的sayhi方法?不this引用cls变量?

4

1 回答 1

1

您正在尝试在 的prototype每个实例上设置属性cls。您真正想要做的是设置自身的prototype属性cls

var Foo = (function () {

    var cls = function () {}; // Constructor function

    cls.prototype = { // Prototype of constructor is inherited by instances
        sayhi: function () {
            alert('hi');
        }
    };

    return cls;

})();
于 2013-03-28T09:40:07.023 回答