Javascript 修改;这";变量
我一直在修改阵列原型,但这一部分让我感到困惑。如果你能帮助我就太好了 好的,假设我想向Array.prototype添加一个函数“Parent”Javascript 修改;这";变量,javascript,Javascript,我一直在修改阵列原型,但这一部分让我感到困惑。如果你能帮助我就太好了 好的,假设我想向Array.prototype添加一个函数“Parent” Array.prototype.Parent = function() { console.log(this); } 接下来,我想在父函数中添加一个子函数。我会这样做: Array.prototype.Parent.Child = function() { console.log(this); } 现在,我希望父级和子级中的这两
Array.prototype.Parent = function() {
console.log(this);
}
接下来,我想在父函数中添加一个子函数。我会这样做:
Array.prototype.Parent.Child = function() {
console.log(this);
}
现在,我希望父级和子级中的这两个都引用数组本身。因此:
[1,2,3].Parent(); // Would output [1,2,3];
[1,2,3].Parent.Child(); // Want it to print [1,2,3];
基本上,我希望child中的这个变量引用数组,而不是父函数。有什么见解吗?这里的问题是,如果有一系列对象查找,然后是函数调用,那么如何识别
这个
变量。像这样
foo.bar.baz.qux();
qux方法的此值等于foo.bar.baz
。
因此,javascript中的函数本质上有一个隐藏的参数this
,这就是它们被调用的对象
无法在javascript中修改此行为。您可以将
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;
},
});
您可以使用
函数.bind重新分配此
var myArray = [1,2,3];
myArray.Parent.Child.bind( myArray )();
在我的示例中,myArray.Parent.Child
是您在示例中定义的函数
,然后我们使用bind
创建函数的副本,将设置为myArray
,然后使用()
操作符调用它
这可以简化为具有自动执行lambda(ES6)的单行:
…这与ES5中的相同:
( function( x ){ return x.Parent.Child.bind( x )() } )( myArray );
这是不可能的。varx=[1,2,3];x、 Parent.Child.bind(x)()
你能把数组作为一个参数传递给函数吗?@Dai,但我不知道x首先要做什么。@code学徒-不能传递参数,不幸的是这个值可以用bind
@Dai更改,他们会把它绑定到什么?绑定到Array.prototype
不会生成[1,2,3]
输出,那么父对象/类不能用作函数=/@nobit:Ah,对不起,它仍然可以是函数;您只需手动附加Child
属性(var f=function(){/*parent things*/};f.Child=function(){/*Child things*/};
)或使用扩展function
的ES6类。这是大量的手动工作,我必须首先了解数组。添加到原型的想法是传播到所有新创建的数组,它的结构我一开始就不知道。
( function( x ){ return x.Parent.Child.bind( x )() } )( myArray );