JavaScript:通过原型函数循环';s变量
我正在尝试这样做:JavaScript:通过原型函数循环';s变量,javascript,Javascript,我正在尝试这样做: var MyFunction = function(Name) { var Handle = this; Handle.Name = Name; } var LoopThroughNames = function() { for(Name in MyFunction) { // This doesn't work. console.log(Name); } } var Handle1 = new MyFunction("H
var MyFunction = function(Name) {
var Handle = this;
Handle.Name = Name;
}
var LoopThroughNames = function() {
for(Name in MyFunction) { // This doesn't work.
console.log(Name);
}
}
var Handle1 = new MyFunction("Hello world!");
var Handle2 = new MyFunction("Test");
LoopThroughNames();
对不起,没有代码标签,我在手机上
var myFunction = function(name) {
var handle = this;
handle.name = name;
}
var loopThroughNames = function() {
for (name in myFunction) {
console.log(name);
}
}
var handle1 = new myFunction("Hello world!");
var handle2 = new myFunction("Test");
loopThroughNames();
它将工作问题在于您的
LoopThroughNames()
实现。您不能迭代MyFunction
,因为它是一个函数声明,但是您可以迭代您创建的Handle1
和Handle2
对象
var LoopThroughNames = function(instanceObject) {
for(Name in instanceObject) {
console.log(instanceObject[Name]);
}
}
LoopThroughNames(Handle1); // "Hello world!"
LoopThroughNames(Handle2); // "Test"
您将类与实例混淆:
Name属性将添加到使用new创建的实例中。
函数MyFunction本身不受这些更改的影响,因此,是的,MyFunction没有自己的属性 编辑:如果您想保留所有内容,请遵循@JuanMendes的想法
创建实例后,您可以将它们存储在一个数组中,为什么不存储它们呢 将此数组作为MyFunction属性使用。
在进行了一些名称更改之后,我建议:
function MyClass(name) {
this.name = name;
MyClass.instances.push(this);
}
MyClass.instances = [];
function printInstancesProperty( targetClass, propName) {
for(var i=0; i< targetClass.instances.length; i++) { // This work.
var instance = targetClass.instances[i];
console.log(instance[propName]);
}
}
var Handle1 = new MyClass("Hello world!");
var Handle2 = new MyClass("Test");
printInstancesProperty(MyClass, 'name');
这是正确的,从另一角度来看,OP可以通过执行< C++ > MyFalue.Stasy.Press(this),将代码初始化为跟踪所有实例,假设
"Hello world!"
"Test"