问题描述
任何人都可以向我解释为什么b返回undefined,以及我如何解决这个问题?为什么当我通过引用调用原型函数时,this范围会丢失?
MyClass = function(test){
this.test = test;
}
MyClass.prototype.myfunc = function(){
return this.test;
}
var a = new MyClass('asd')。myfunc();
var b = new MyClass('asd')。myfunc;
//正确返回asd
console.log(a)
//返回未定义??
console.log(b())
===编辑/解决方案===
正如plalx写道的,在我的例子中正确的解决方案是使用.bind()。所以结果如下所示:
MyClass = function(test){
this.test = test;
}
MyClass.prototype.myfunc = function(){
return this.test;
}
var a = new MyClass('asd')。myfunc();
var b = new MyClass('asd'),
bfunc = b.myfunc.bind(b)
//正确返回asd
控制台。日志(a)
//也正确返回asd!
console.log(bfunc())
你需要明确地绑定这个值,如果你想要这样的行为。
$ $ $ $ $ $ c $ var c = new MyClass('asd'),
b = c.myfunc.bind(c);
console.log(b());
默认情况下,这个
会指向 leftSide.ofTheDot();
在调用中,或者简单地调用该函数的对象。
注意:调用 将每个函数绑定到对象实例是可能的,但效率很低,因为函数不会再跨实例共享。 Eg Can anyone explain to me why "b" returns undefined and how I can get around this problem? Why does the "this" scope get lost when I call prototype functions by reference? === EDIT / SOLUTION === As plalx writes, the correct solution in my case is to use .bind(). So the result looks like this: You need to explicitely bind the this value if you want this behaviour. By default, Note: Calling Binding every function to the object instance is possible but rather inefficient because functions will not get shared across instances anymore. E.g. 这篇关于班级失去“这个”通过引用调用原型函数时的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! b();
与 window.b(); $ c $
function MyClass(someVal){
var me = this;
me.someVal = someVal;
me.someFn = function(){
return me.someVal;
};
}
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd').myfunc;
// Returns "asd" correctly
console.log(a)
// Returns undefined??
console.log(b())
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd'),
bfunc = b.myfunc.bind(b)
// Returns "asd" correctly
console.log(a)
// Also returns "asd" correctly!
console.log(bfunc())
var c = new MyClass('asd'),
b = c.myfunc.bind(c);
console.log(b());
this
will point to the leftSide.ofTheDot();
in an invocation, or simply the object on which the function was called.b();
is the same as window.b();
.function MyClass(someVal) {
var me = this;
me.someVal = someVal;
me.someFn = function () {
return me.someVal;
};
}