当我从nodejs启动时,这为什么起作用:
var a = function (name) {
return "Hello, " + name.toUpperCase();
};
var result = a("bob");
console.log(result)
但是这个:
var A = (function () {
function A(msg) {
this.msg = " ";
this.msg = msg;
}
A.prototype.hello = function (name) {
return "Hello, " + name.toUpperCase();
};
A.prototype.helloToBob = function (fn) {
return fn.apply("Bob");
};
return A;
})();
var test = new A("some message");
var msg = test.hello("Bob1");
var msg2 = test.helloToBob(test.hello);
console.log(msg);
失败与:
return "Hello, " + name.toUpperCase(); ^ TypeError: Cannot call method 'toUpperCase' of undefined
?
从TypeScript代码生成/编译的JS代码。(无错误编译)
问题出在这行代码中。
return fn.apply("Bob");
这里有几个问题。
的第一个参数必须.apply(obj, arrayOfArguments)
是您要this
在方法调用期间将指针设置为的对象。
的第二个参数.apply()
是参数数组,而不是单个参数。
这是一个可能的解决方案,您将其this
用作对象并切换到该位置,fn.call()
因为fn.apply()
它接受一个参数数组,但是只有一个参数。
更改此:
return fn.apply("Bob");
对此:
return fn.call(this, "Bob");
并且,所有代码在一起:
var A = (function () {
function A(msg) {
this.msg = " ";
this.msg = msg;
}
A.prototype.hello = function (name) {
return "Hello, " + name.toUpperCase();
};
A.prototype.helloToBob = function (fn) {
return fn.call(this, "Bob");
};
return A;
})();
var test = new A("some message");
var msg = test.hello("Bob1");
var msg2 = test.helloToBob(test.hello);
console.log(msg);
仅供参考,还有其他解决方案。您也可以这样做:
var A = (function () {
function A(msg) {
this.msg = " ";
this.msg = msg;
}
A.prototype.hello = function (name) {
return "Hello, " + name.toUpperCase();
};
A.prototype.helloToBob = function (fn) {
return fn("Bob");
};
return A;
})();
var test = new A("some message");
var msg = test.hello("Bob1");
var msg2 = test.helloToBob(test.hello.bind(test));
console.log(msg);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句