JavaScript从其函数中调用getter

时间:2014-11-04 18:33:28

标签: javascript getter-setter

尝试在伪代码中执行以下操作:

(function(scope) {

    scope.doSomenthin = function() {

        if (x === y && this.onfinish) {
            //  If exists, run onfinish,  should return 'fin'
            this.onfinish();
        }
    }

})(scope);

window.scope = window.scope || (window.scope = {});
scope.doSomenthin().onfinish = function(){return 'fin'}

如果存在onfinish,则在运行时运行该功能。尝试使用getter / setter,但此时它将返回undefined。设置超时有效但不是我想做的事。

还有其他想法吗?感谢。

3 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解这个问题,但我认为你想要的是为你正在调用的函数设置上下文。这就是你要追求的吗?

//create a function that accesses an object's properties and methods with 'this'
var doSomethin = function() {
    var result = "nonfinish";

    if (this.onfinish) {
        //  If exists, run onfinish,  should return 'fin'
      result = this.onfinish();
    }

    return result;
}

//add an 'onfinish' method to the 'scope' object
scope = {
    onfinish: function(){return 'fin'}
}

//run the accessor function in the window context
alert(doSomethin());

//run the accessor function in scope's context
alert(doSomethin.call(scope));

答案 1 :(得分:0)

我发现您的代码存在多处错误。这可能是您试图实现的结果..

window.scope = window.scope || (window.scope = {});
scope.onfinish = function(){return 'fin'};

(function(scope) {

    scope.doSomenthin = function() {

        if (this.onfinish) {
            //  If exists, run onfinish,  should return 'fin'
            return this.onfinish();
        }
    }

})(scope);

alert(scope.doSomenthin());

  • 在此处创建临时范围时,请将scope作为a 参数。但scope尚未定义。

    (function(scope) {
    
      scope.doSomenthin = function() {
    
        if (x === y && this.onfinish) {
            //  If exists, run onfinish,  should return 'fin'
            this.onfinish();
        }
      }
    
    })(scope);   
    
  • 您的scope.doSomenthin函数不会返回任何值。因为 其中scope.doSomenthin()的值是未定义的。因此 与scope.doSomenthin().onfinish = function(){return 'fin'}你 正试图设置一个不分割的属性。

答案 2 :(得分:0)

您想要接近的是类似于事件驱动的编程。不要只是立即调用该函数,而是将其注册为事件处理程序。以下伪代码仅显示了我的想法。它不完整

//register the function here, instead of calling it immediately
event = document.createEvent("HTMLEvents");
event.initEvent("myEvent", true, true);
document.addEventListener("myEvent", function(e) {
    e.scope.doSomenthin = function() {

        if (this.onfinish) {
            //  If exists, run onfinish,  should return 'fin'
            return this.onfinish();
        }
    }
});

......

//call the handler to handle the below event
window.scope = window.scope || (window.scope = {});
scope.doSomenthin().onfinish = function(){return 'fin'}
event.scope = scope;
document.body.dispatchEvent(event);

上面的代码有点傻。您必须设计放置和触发事件的位置。