JS:原型实例

时间:2017-01-05 14:13:37

标签: javascript javascript-objects

至于JS新手,我正在努力解决JS-closure问题。用Google搜索足够了,但无法理解为什么“这个”在“商店”功能中不可用。任何帮助将不胜感激:

;(function (win) {
var _af = function(storeObjectName, storeObjectValue) {
    var self;
    if (_af.prototype.instance) {
        self = _af.prototype.instance;
    } else {
        self = Object.create(_af.prototype);
        _af.prototype.instance = self;
        self._init();
    }
    if (arguments.length == 1) return self.fire(storeObjectName);
    if (arguments.length == 2) self.store(storeObjectName, storeObjectValue);
    return self;
};

_af.prototype = {
    afVariable: '_af',
    afObject: {},

    _init : function(){
        this.afObject = this.get(self.afVariable);
    },

    store : (storeObjectName, storeObjectValue)=>{
        // This throws the error, that this.get is not defined
        this.get('_af');
    },

    get : storageObject=>{
        if (!storageObject)
            this.afObject = '_af';
        else
            this.afObject = '_someother'
    }
}
win._af = _af;
}(window));

1 个答案:

答案 0 :(得分:2)

这是因为您使用lambda expression(...) => ...)代替function() { ...

JS this在很大程度上依赖于上下文。在您的情况下,由于原型是一个对象,每当您想使用this来引用该对象时,您必须在对象中定义的函数中执行此操作,如:

store : function(storeObjectName, storeObjectValue) {
    // This throws the error, that this.get is not defined
    this.get('_af');
},

或(也正确):

store(storeObjectName, storeObjectValue) {
    // This throws the error, that this.get is not defined
    this.get('_af');
},

请注意,您正在为_init正确执行此操作,但不适用于storeget

当你使用lambda语法时,this会在创建函数时引用当前的语法,因此它将是window

同时避免将get用作函数/或任何其他名称,因为它用于定义getter。