[英]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);
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); })()
b
to remain unaffected by function hoisting)
b
不受功能提升的影响,必须具有功能魔术师)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.