【问题标题】:Passing parameters to object or inherit object's function?将参数传递给对象或继承对象的功能?
【发布时间】:2012-08-14 14:49:38
【问题描述】:

WSFunctions[this.name](); 执行的第二个console.log() 将打印undentified。我想知道我是否能够以某种方式在我的Call() 函数中使用inherit DoThisAndThat。我不想以WSFunctions[this.name](this.params) 的方式传递参数,因为随着项目的发展,可能有超过this.params 可以传递。

function WS(name, params) {
    this.name = name;
    this.params = params;
}

WS.prototype.Call = function() {
    if (typeof WSFunctions[this.name] !== "function") {
        return false;
    }

    console.log(this.params);
    WSFunctions[this.name]();

    return true;
}

var WSFunctions = {
    'ScreenRightGuest': function() {
        // .. whatever ..
        return true;        
    },
    'DoThisAndThat': function() {
        console.log(this.params);
        return true;
    }
}


new WS('DoThisAndThat', { login: '123', pass: 'abc' }).Call();

提前致谢 迈克

【问题讨论】:

  • 或者你可能有不同的建议如何构建它,我只是从 JavaScript“类”开始。
  • 这实际上与“类”或继承或原型无关,仅与 this 和调用函数的工作方式有关,
  • 是的,这是一个非常奇怪的模式。您正在构建一个对象的实例,并使用该对象的“属性”来引用该类型的“静态函数”。
  • 这个想法是将来只需添加新功能就可以自定义var WSFunctions。此外,它们将使用 new WS('name', ) 调用。有 Call() 作为原型,将来还会有更多,Reload()、Copy() 等
  • WSFunctions 作为外部依赖似乎仍然很奇怪。您也应该将它们分配给原型,或者将它们作为参数传递给WS

标签: javascript function object inheritance prototype


【解决方案1】:

您可以使用.call [MDN].apply [MDN] 明确设置this 应在函数中引用的内容

WSFunctions[this.name].call(this);

这将调用WSFunctions[this.name],并将this 设置为调用者中this 所指的内容(在本例中为new WS(...) 创建的实例)。

还可以查看this page,它彻底解释了this 的工作原理。

【讨论】:

  • 当然谢谢你成功了,如果你能在第一篇文章中关注我,我会很高兴。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多