简体   繁体   English

修改“ this”变量

[英]Modifying “this” variables

I was playing around with modifying Array Prototype, but I'm stumped at this part. 我当时在修改数组原型,但是我对此感到困惑。 Would be great if you could help me. 如果您能帮助我,那就太好了。

Alright, suppose I want to add a function "Parent" to Array.prototype 好吧,假设我要向Array.prototype添加函数“ Parent”

Array.prototype.Parent = function() { 
    console.log(this);
}

Next, I want to add a Child function to the Parent function. 接下来,我要向父函数添加子函数。 I would do it like this: 我会这样做:

Array.prototype.Parent.Child = function() { 
    console.log(this);
}

Now, I want both this in Parent and Child to refer to the array itself. 现在,我希望在“父级”和“子级”中都引用数组本身。 So: 所以:

[1,2,3].Parent(); // Would output [1,2,3];
[1,2,3].Parent.Child(); // Want it to print [1,2,3];

Basically, I want this variable in child to refer to the array instead of the Parent Function. 基本上,我希望子级中的此变量引用数组而不是父函数。 Any insight? 有见识吗?

You can make Parent a getter that returns a unique function for each array, providing context: 您可以使Parent为获取器,为每个数组返回唯一的函数,并提供上下文:

Object.defineProperty(Array.prototype, 'parent', {
    configurable: true,
    get: function () {
        var that = this;

        function parent() {
            console.log(that);
        }

        parent.child = function () {
            console.log(that);
        };

        return parent;
    },
});

The problem here is how the this variable is identified if you have a series of object lookups then a function call. 这里的问题是,如果您先进行一系列对象查找,然后进行函数调用,则如何识别this变量。 Like this. 像这样。

foo.bar.baz.qux();

The qux method has a this value equal to foo.bar.baz . qux方法的this值等于foo.bar.baz So in essence functions in javascript have a hidden argument this that is the object they are called on. 因此,从本质上讲,javascript中的函数具有一个隐藏的参数, this是它们被调用的对象。

There is no way to modify this behavior in javascript. 无法在javascript中修改此行为。

You can reassign this using Function.bind . 您可以使用Function.bind重新分配this

var myArray = [1,2,3];

myArray.Parent.Child.bind( myArray )();

In my example, myArray.Parent.Child is the Function you defined in your example - then we use bind to create a copy of the function with this set to myArray , then we use the () operator to invoke it. 在我的例子, myArray.Parent.ChildFunction ,你在你的例子定义-然后我们用bind创建函数的副本, this设置为myArray ,然后我们使用()操作符来调用它。

This can be reduced to a single line with a self-executing lambda (ES6): 可以使用自动执行的lambda(ES6)将其减少为一行:

( x => x.Parent.Child.bind( x )() )( myArray );

...which is equivalent to this in ES5: ...等效于ES5:

( function( x ){ return x.Parent.Child.bind( x )() } )( myArray );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM