将此对象传递给JavaScript中的内部函数
我有一个函数定义在另一个函数,就像这样
function Test(message) { this.message = message; } Test.prototype.print = function() { console.log(this.message); } Test.prototype.print.polite = function() { console.log(this.message + ', please.'); } var x = new Test('hello world'); x.print(); x.print.polite();
x.print()按预期打印“hello world”,但是x.print.polite()打印'undefined,please',而不是'hello world'。
我明白这是因为传递给print.polite函数的上下文是打印函数。 但是,是否有一种方法可以从print.polite访问print的“this”,而不是明确地将其添加为参数? 我想保留print.polite()的调用语义,而不是使其成为printPolite()。
我相当新的JavaScript,所以我很抱歉,如果这是一个愚蠢的问题。
编辑
基于这些build议,我已经修改了我的代码,似乎是这样工作的。
function Test(message) { this.message = message; this.print.that = this; } Test.prototype.print.polite = function() { console.log(this.that.message + ', please.'); }
就像你指出的那样,这是一个相当不好的解决办法。 没有更好的方法来做到这一点?
你将不得不使用call
或apply
,像这样:
Test.prototype.print.polite.call(x);
这将调用函数Test.prototype.print.polite
以x
作为上下文,或者this
值,并且没有参数。
可以保持调用的语义,但实现可能有点难看。
function Test(message) { var local = this; this.message = message; this.print = function() { console.log(local.message); }; this.print.polite = function() { console.log(local.message + ", please."); }; return this; }
请注意,这根本不利用原型。