为什么这在我从 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);
关于javascript - 未定义的 NodeJS 'toUpperCase'(从 typescript 生成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378839/