在变量实例上访问原型方法

Accessing prototype method on variable instance

本文关键字:原型 方法 访问 变量 实例      更新时间:2023-09-26
var Foo = (function () {
    var cls = function () {
        this.prototype = {
            sayhi: function () {
                alert('hi');
            }
        };
    };
    cls.staticMethod = function () {};
    return cls;
})();
var f = new Foo();

为什么我不能访问我的sayhi方法?this不是指cls变量吗?

您试图在cls的每个实例上设置prototype属性。你真正想做的是设置cls本身的prototype属性:

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