班级失去“这个”通过引用调用原型函数时的范围 [英] Class loses "this" scope when calling prototype functions by reference

查看:105
本文介绍了班级失去“这个”通过引用调用原型函数时的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释为什么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(); 在调用中,或者简单地调用该函数的对象

注意:调用 b(); window.b();

将每个函数绑定到对象实例是可能的,但效率很低,因为函数不会再跨实例共享。



Eg

  function MyClass(s​​omeVal){
var me = this;

me.someVal = someVal;

me.someFn = function(){
return me.someVal;
};
}


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?

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())

=== EDIT / SOLUTION ===

As plalx writes, the correct solution in my case is to use .bind(). So the result looks like 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'),
    bfunc = b.myfunc.bind(b)

// Returns "asd" correctly
console.log(a)

// Also returns "asd" correctly!
console.log(bfunc())

解决方案

You need to explicitely bind the this value if you want this behaviour.

var c = new MyClass('asd'),
    b = c.myfunc.bind(c);


console.log(b());

By default, this will point to the leftSide.ofTheDot(); in an invocation, or simply the object on which the function was called.

Note: Calling b(); is the same as window.b();.

Binding every function to the object instance is possible but rather inefficient because functions will not get shared across instances anymore.

E.g.

function MyClass(someVal) {
    var me = this;

    me.someVal = someVal;

    me.someFn = function () {
        return me.someVal;
    };
}

这篇关于班级失去“这个”通过引用调用原型函数时的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆