我正在试图弄清楚如何从构造函数到其中一个原型函数获取函数上下文。但是当我检查原型函数中的'this'值时,它只是将它显示为'Object'而不是调用(ctor)上下文。
所以我有代码:
function CL(){
...
(stuff)
...
console.log(this);
protoFunc(this);
}
CL.prototype.protoFunc = function(context) {
var self = context;
console.log(context);
...
}
调用protoFunc之前的函数上下文是CL的函数上下文。但是在protoFunc中它是[Object object]。
如何将函数上下文转换为protoFunc?
感谢。
莱斯
答案 0 :(得分:3)
您无法像这样致电protoFunc
,前方需要this
。你没有收到错误吗?代码应该是:
function CL(){
...
(stuff)
...
console.log(this);
this.protoFunc();
}
这会在原型方法中为您提供正确的this
- CL
通过new
正确调用:
var instance = new CL();
答案 1 :(得分:1)
你甚至不需要这样做。试试这个:
function CL(name) {
//for example...
this.name = name;
}
CL.prototype.protoFunc = function () {
console.log(this);
};
然后你必须用你的构造函数实例化一个对象......
var x = new CL('Bob');
x.protoFunc();
//=> logs {name: 'Bob'}
如果你试图将ACTUAL CONSTRUCTOR FUNCTION纳入你的方法,你也不需要任何技巧。
CL.prototype.protoFunc = function () {
var cTor = CL;
console.log(cTor);
};
这就是你要找的东西,还是你想要得到别的东西?
修改强>
如果你想在构造函数中调用prototype函数,你应该这样做:
function protoFunc() {
console.log(this);
}
function CL(name) {
protoFunc.call(this);
}
CL.prototype.protoFunc = protoFunc;
答案 2 :(得分:1)
函数的此值可以通过调用函数的方式设置,也可以使用Function.prototype.bind设置。
假设:
function CL(){
console.log(this); // a new object
protoFunc(this); // protoFunc doesn't exist on CL's scope chain and will throw an error
}
如果按如下方式调用CL(假设尚未使用 bind ):
CL()
其此值尚未设置,因此在非严格模式下on entering the function将设置为全局(窗口)对象。在严格模式下,它将是 undefined 。
如果使用 new 调用CL:
var cl = new CL()
然后函数中的将引用一个新的Object,就好像new Object()
一样,即它是对实例的引用。由于默认情况下返回此新对象,并且此处将其分配给 cl ,因此保留了对构造函数 this 的引用,不需要保留任何其他对象参考
请注意,每次调用CL都会创建一个全新的执行上下文。
如果您创建CL的实例,然后调用分配给构造函数原型的方法,如:
cl.protoFunc()
然后 protoFunc 中的将 cl 。
您的陈述:
调用protoFunc之前的函数上下文是CL
的函数上下文
没有意义,大概在这里你会把“背景”与“这个”混淆。如上所述,此是由调用(或绑定)设置的,因此您必须显示如何调用 CL 以确定这是什么将会。
如何将函数上下文添加到protoFunc
中
鉴于构造函数中的是实例,并且函数的此值由调用设置:
cl.protoFunc()
将完成这项工作。
术语“上下文”作为 this 的假名已经悄悄进入ECMAScript术语,这是不幸的。 ECMA-262将execution context定义为在进入函数(或新的全局环境或使用eval时)时创建的环境,该环境包括范围链和函数的所有变量,包括其 this 价值。您无法以任何方式引用执行上下文或访问它。
因此,函数的上下文不仅仅是 this 。