【问题标题】:best way for add scope reference in function在函数中添加范围引用的最佳方法
【发布时间】:2018-06-23 01:52:02
【问题描述】:

嗨,伙计,将作用域 obj 引用添加到函数的最佳方法是什么。

我的例子,我有一个超级对象。

var SuperObj = new PIXI.sprite();

SuperObj.action = new subObj();

SuperObj.action.actionFunction = function(){// need to acces to SuperObj};

当我将函数 stuf 添加到操作时,我需要添加对其父级的范围引用。

所以我需要从 subObj 在我的函数中加入 SuperObj

所以在我的上下文中,最好这样进行?

var motion = this._motions[motionName];
var action = (function(motion,actions){

    return function(){
        console.log('actions: ', actions); // by closures
    };
})(motion,this); // this scoped by closures in function
this.actions.add_newAction(action,motionName,actionName);

或者这样

var motion = this._motions[motionName];
var action = (function(motion){

    return function(){
        console.log('actions: ', this.scoped ); // by scope obj
    };
})(motion); action.scoped = this;
this.actions.add_newAction(action,motionName,actionName);

什么是最有效的方式,或者你有其他建议方式? 我需要性能最佳和最实用的方式。 谢谢

【问题讨论】:

    标签: javascript performance scope closures


    【解决方案1】:

    如果它需要访问超级 obj,它可能应该在超级 obj 中。

    在超类中,您可以将子类作为属性访问。

    所以,方法应该是这样的:

    SuperObj.addActionFunction = function(){// need to acces to SuperObj};
    

    actions 是基于上述内容的(动作类的)列表,而不是 superobj 的直接属性,如果您需要访问该列表,另一个原因应该在 superobj 中。

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多