2012-08-14 216 views
0

console.log()执行WSFunctions[this.name]();将打印undentified。我想知道我是否能够inheritDoThisAndThat在我的Call()函数。我不想以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(); 

在此先感谢 麦克

+0

或者你可能有不同的建议,如何构建,我刚刚开始使用JavaScript“类”。 – Mike 2012-08-14 14:51:09

+0

这与“类”或继承或原型没有任何关系,只与“this”和调用函数的工作方式有关, – 2012-08-14 14:56:31

+0

是的这是一个非常奇怪的模式。您正在构建对象的实例,并使用此对象的“属性”引用该类型的“静态函数”。 – dievardump 2012-08-14 14:56:33

回答

0

您可以明确设置什么this应该是指在函数中调用.call[MDN].apply[MDN]

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

这将调用WSFunctions[this.name]this被设置到什么this指主叫方(在这种情况下,由new WS(...)创建的实例)。

也看看this page,它彻底解释如何this的作品。

+0

当然,谢谢你这样做,如果你能在第一篇文章中留言,我会很高兴。 – Mike 2012-08-14 15:06:31