简体   繁体   English

覆盖Javascript中的全局函数

[英]Overriding global functions in Javascript

After overriding the Array function, why the behavior of the two objects is different? 重写Array函数后,为什么两个对象的行为不同?

 function Array(){} var array1 = ['1','2'] var array2 = new Array(); console.log(array1.length); // 2 console.log(array2.length); // undefined 

Also, Object() returns an empty object instance but with a user-defined function, we must use new operator, why? 另外, Object()返回一个空的对象实例,但是带有用户定义的函数,我们必须使用new运算符,为什么?

That ( Object() without new ) is a shortcut, which you can provide too: (没有new Object() )是一个快捷方式,您也可以提供:

 function Stuff(x){ if(!(this instanceof Stuff)){ console.log("You forgot 'new'"); return new Stuff(x); } this.x=x; } var a=Stuff(1); var b=new Stuff(2); console.log(a,b); 
And yes, when you locally override the built-in Array , you are stuck with that one. 是的,当您在本地覆盖内置Array ,您将无法使用它。 But already existing arrays remain to be original, they do not get fitted retroactively to your own type, and the [] syntax is not affected by your override (case of c ): 但是已经存在的数组仍然是原始数组,它们无法追溯性地适合您自己的类型,并且[]语法不受覆盖的影响( c ):

 var a=[1,2]; var b=new Array(3,4); (function(){ function Array(){} var c=[1,2]; var d=new Array(3,4); console.log("a:",a); console.log("b:",b); console.log("c:",c); console.log("d:",d); })() 
(The function-magic is necessary for b to remain unaffected by function hoisting) (要使b不受功能提升的影响,必须具有功能魔术师)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM