我正在玩修改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。有什么见解吗?
答案 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 );