[英]Looping through a “function” object in javascript
i have this project where i would like to merge a "function" object (in contrast to the JSON object - an object literal) with an existing object. 我有一个项目,我想将一个“功能”对象(与JSON对象-对象文字相反)与现有对象合并。 i would want to get the "publicly visible" properties.
我想获取“公开可见”属性。 however, when i do a for in loop, they don't show up.
但是,当我进行for in循环时,它们不显示。 they don't trigger the
console.log()
inside. 它们不会触发内部的
console.log()
。 how do i get them? 我如何获得它们?
//obj passed to extend() by external caller
//this is what obj it looked like when i console.log()'ed it
obj = function() {
//skip these private ones
var imPrivate = 'i should not be included';
function imGetter() {}
//i want these guys below:
this.getter = imGetter;
this.imPublic = "i should be included";
}
function extend(obj){
console.log('i can see here');
for (var key in obj) {
console.log('you cannot see here');
}
//...more of our code here
}
Those properties don't exist until you call the function. 在调用函数之前,这些属性不存在。
Once you var foo = new obj();
一旦你
var foo = new obj();
then you will see the properties (on foo
). 然后您将看到属性 (在
foo
)。
Alternatively, move the code that sets the properties so it is outside the function . 或者,移动设置属性的代码,使其位于函数外部 。
you could make it self execute: 您可以使其自行执行:
var obj={};
(function(ns) { //skip these private ones
var imPrivate = 'i should not be included';
function imGetter() {};
//i want these guys below:
ns.getter = imGetter;
ns.imPublic = "i should be included";
})(obj)
console.log('i can see here');
for (var key in obj) {
console.log('you cannot see here '+key+" holds:"+obj[key]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.