Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript将原型设置为对象_Javascript - Fatal编程技术网

JavaScript将原型设置为对象

JavaScript将原型设置为对象,javascript,Javascript,我正在尝试让以下代码正常工作 Array.prototype.test = { func: function() { console.log(this); return this; } }; 然后当我运行以下命令时 [].test.func(); 问题是该函数中的这个是对象数组。prototype.test不是我传入的数组 我觉得必须有办法做到这一点,而不必将Array.prototype.test设置为函数,并像调用[].test().fun

我正在尝试让以下代码正常工作

Array.prototype.test = {
    func: function() {
        console.log(this);
        return this;
    }
};
然后当我运行以下命令时

[].test.func();
问题是该函数中的
这个
是对象
数组。prototype.test
不是我传入的数组

我觉得必须有办法做到这一点,而不必将
Array.prototype.test
设置为函数,并像调用
[].test().func()那样调用它

Chai经常使用这种语法。所以我认为这是可能的


我如何才能让它像我期望的那样工作?

JavaSript并没有一个很好的方法来访问它

您可以使用一个getter for
test
,它返回一个带有绑定方法的函数

Object.defineProperty(Array.prototype,'test'{
对,,
可枚举:false,
get:function(){
返回{
func:function(){
console.log(this);
归还这个;
}.绑定(此)
};
}
});

[].test.func()JavaSript并没有一个很好的访问方法

您可以使用一个getter for
test
,它返回一个带有绑定方法的函数

Object.defineProperty(Array.prototype,'test'{
对,,
可枚举:false,
get:function(){
返回{
func:function(){
console.log(this);
归还这个;
}.绑定(此)
};
}
});

[].test.func()为什么不Array.prototype.test=function(){console.log(this);返回这个;}@xianshenglu我在问题中提到过这个。因为我看到了另一种方式,所以我很确定这是可能的。柴就是一个很好的例子。在我看来,我试图实现的语法更加简洁,更好地满足了我的需求。它也意味着一种学习体验,而不是通过尝试探索一种新的方法来寻找廉价的出路。为什么不Array.prototype.test=function(){console.log(this);return this;}@xianshenglu我在问题中提到过这一点。因为我看到了另一种方式,所以我很确定这是可能的。柴就是一个很好的例子。在我看来,我试图实现的语法更加简洁,更好地满足了我的需求。它也意味着一种学习体验,而不是通过尝试探索一种新的学习方法来寻求廉价的出路。非常详细和解释。非常感谢你的回答。是的,我完全可以看到它是多么的复杂,但是理解JS的内部工作还是很棒的。谢谢非常详细和解释。非常感谢你的回答。是的,我完全可以看到它是多么的复杂,但是理解JS的内部工作还是很棒的。谢谢