简体   繁体   English

JavaScript对象创建及其原型

[英]JavaScript Object Creation and its Prototype

I create an Object in JavaScript: 我用JavaScript创建一个对象:

var object = {value1 : "value1", value2 : "value2"};

If I now try and count the contents of 'object.prototype' I get the result 0. If I add properties I get the correct result. 如果现在尝试计算“ object.prototype”的内容,则结果为0。如果添加属性,则结果正确。 Am I to take it then that 'object.prototype' is in fact empty? 我是否认为'object.prototype'实际上为空?

Thanks! 谢谢!

If you want to iterate through all the properties you assigned to your object, you can just do it with a for..in loop: 如果要遍历分配给对象的所有属性,只需使用for..in循环即可:

for (var prop in object){
    if (object.hasOwnProperty(prop)){
        var propValue = object[prop];
        // ...
    }
}

If you need to count the properties, you can just increment a counter on each iteration. 如果需要计算属性,则可以在每次迭代时增加一个计数器。

In Javascript, by DEFAULT only "function objects" have a prototype property.. 在Javascript中,默认情况下,只有“函数对象”具有原型属性。

for example, none of the following have a prototype property by default - 例如,以下所有默认情况下都不具有原型属性-

var a = new Object();
var b = {};
var a = new Array();
var b = [];

But, 但,

var a = function() {};

has a prototype property.. and by default - 具有原型属性。默认情况下-

a.prototype is {constructor : this}

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

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