修改“this”变量

时间:2017-07-23 06:05:38

标签: javascript

我正在玩修改Array Prototype,但我对这部分感到难过。如果你能帮助我会很棒。

好吧,假设我想在Array.prototype

中添加一个函数“Parent”
Array.prototype.Parent = function() { 
    console.log(this);
}

接下来,我想在Parent函数中添加一个Child函数。我会这样做:

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

现在,我想在Parent和Child中同时引用数组本身。所以:

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

基本上,我希望child中的这个变量引用数组而不是Parent Function。有什么见解吗?

3 个答案:

答案 0 :(得分:2)

你可以让Parent为每个数组返回一个唯一函数的getter,提供上下文:

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;
    },
});

答案 1 :(得分:0)

这里的问题是如果你有一系列的对象查找然后是一个函数调用,那么如何识别this变量。像这样。

foo.bar.baz.qux();

qux方法的此值等于foo.bar.baz。 所以本质上javascript中的函数有一个隐藏的参数this,它是被调用的对象。

无法在javascript中修改此行为。

答案 2 :(得分:0)

您可以使用this重新分配Function.bind

var myArray = [1,2,3];

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

在我的示例中,myArray.Parent.Child是您在示例中定义的Function - 然后我们使用bind创建函数的副本,this设置为{{ 1}},然后我们使用myArray运算符来调用它。

这可以简化为具有自执行lambda(ES6)的单行:

()

......这与ES5中的相同:

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