gpt4 book ai didi

javascript - 修改 "this"变量

转载 作者:行者123 更新时间:2023-11-30 15:09:54 25 4
gpt4 key购买 nike

我一直在尝试修改 Array Prototype,但我对这部分感到困惑。如果你能帮助我,那就太好了。

好吧,假设我想向 Array.prototype 添加一个函数“Parent”

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

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

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

现在,我希望 Parent 和 Child 中的 this 都引用数组本身。所以:

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

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

最佳答案

您可以使 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;
},
});

关于javascript - 修改 "this"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com