简体   繁体   English

如何将原型属性从javascript中的超类委托给子类

[英]how prototype properties are delegated to sub class from super class in javascript

Please help me to understand following code snippet. 请帮助我了解以下代码段。

var ob = {a:20,b:30};
Object.prototype.c = '40';
for (var x in ob){
    console.log(x); // will log a,b,c in console
}
var keys = Object.keys(ob) ;
console.log(keys); // will log a,b in console

My question is that , How putting property 'c' on the prototype of 'Object' will make it available to 'ob' ? 我的问题是,如何将属性“ c”放到“对象”的原型上,才能使其对“对象”可用?

Edit: Basically I want to know which default constructor function is called when we try to create an object and what are the basic responsibilities performed by the constructor ? 编辑:基本上我想知道当我们尝试创建对象时调用哪个默认构造函数,构造函数执行的基本职责是什么?

The Object.keys() method returns an array of a given object's own enumerable properties, the difference being that a for-in loop enumerates properties in the prototype chain as well, so Object.keys(ob) will enumerate only ob own property not the property of ob prototype Object.keys()方法返回给定对象自己的可枚举属性的数组,不同之处在于for-in循环也枚举了原型链中的属性,因此Object.keys(ob)将只枚举ob自己的属性,而不会枚举ob prototype的属性

Object Properties 对象属性

Object.prototype.constructor --> Specifies the function that creates an object's prototype. Object.prototype.constructor >指定用于创建对象原型的函数。

Object.prototype.__proto__ --> Points to the object which was used as prototype when the object was instantiated. Object.prototype.__proto__ >指向实例化对象时用作原型的对象。

Object.prototype.__noSuchMethod__ --> Allows a function to be defined that will be executed when an undefined object member is called as a method. Object.prototype.__noSuchMethod__ >允许定义一个函数,当将未定义的对象成员称为方法时,将执行该函数。

An object literal ( {} ) will inherit from Object.prototype . 对象文字( {} )将继承Object.prototype Object.prototype.c = '40'; sets the c property on Object 's prototype, so all objects inheriting from Object will be able to access this property. Object的原型上设置c属性,因此从Object继承的所有对象都将能够访问此属性。 Any properties defined on Object 's prototype will be accessible on objects inheriting from it. Object原型上定义的任何属性都可以在继承自其原型的对象上访问。

The difference between for (var x in ob) and Object.keys(ob) is that Object.keys(ob) will return only the properties of the ob object, whereas for (var x in ob) will traverse the prototype chain and find the c property on Object 's prototype. for (var x in ob)Object.keys(ob)之间的区别在于Object.keys(ob)仅返回ob对象的属性,而for (var x in ob)将遍历原型链并查找Object原型上的c属性。

By default, no properties defined on Object 's prototype will be included in a for-in loop as they are not enumerable. 默认情况下,由于无法枚举,因此在for-in循环中不包含在Object原型上定义的属性。 An added property is enumerable by default. 默认情况下,添加的属性是可枚举的。

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

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