[英]why every javascript object has constructor property?
Just trying to understand why every JavaScript object has a constructor property. 只是想了解为什么每个JavaScript对象都具有构造函数属性。
Is there any use of constructor property because object is already created? 因为已经创建了对象,所以可以使用构造函数属性吗?
var MyFunc = function (name){this.name=name}
var instance = new MyFunc("myclass");
now instance has a constructor property which has reference to MyFunc itself. 现在实例具有一个构造函数属性,该属性引用了MyFunc本身。 What is use of having constructor property on instance? 在实例上具有构造器属性有什么用?
It is (much) more complicated than that : no object, in, JS has a constructor
property by default, but their prototype (if the object has a prototype) have one. 比这要复杂得多:在默认情况下,JS没有对象具有constructor
属性,但是其原型 (如果对象具有原型)只有一个。
Also, be careful : the constructor
references a function, but this prototype property is not read-only, so one can easily change the property, therefore do not rely on it. 另外,请注意: constructor
引用了一个函数,但是此原型属性不是只读的,因此可以轻松更改该属性,因此不要依赖它。
Does this answer your question ? 这回答了你的问题了吗 ?
var dog1= {"a":1}
function Dog ()
{
}
dog2= new Dog();
console.log(dog1.constructor) //function Object() { [native code]...
console.log(dog2.constructor) //function Dog()...
Sometimes you need to know how object was created. 有时您需要知道对象是如何创建的。 ( not to mention that prototype is a constructor property) (更不用说原型是构造函数属性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.