我试图弄清楚如何将函数上下文从构造函数获取到它的原型(prototype)函数之一。但是,当我检查原型(prototype)函数中的“this”值时,它只是将其显示为“对象”,而不是调用(ctor)上下文。
所以我有代码:
function CL(){
...
(stuff)
...
console.log(this);
protoFunc(this);
}
CL.prototype.protoFunc = function(context) {
var self = context;
console.log(context);
...
}
调用protoFunc之前的函数上下文是CL的。但在protoFunc中它是[Object对象]。
如何将函数上下文放入 protoFunc 中?
谢谢。
莱斯
最佳答案
你不能像这样调用protoFunc
,你需要在前面加上this
。你没有收到错误吗?代码应该是:
function CL(){
...
(stuff)
...
console.log(this);
this.protoFunc();
}
这将为您在原型(prototype)方法中提供正确的 this
- 前提是使用 new
正确调用 CL
:
var instance = new CL();
关于javascript - 调用原型(prototype)函数时丢失函数上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19147006/