我需要运行属于对象的所有实例的方法。例如,如果我有方法fullName(),它连接.firstName和.secondName,我想为代码中的对象的两个实例执行此操作:
<script>
function x(firstName, secondName) {
this.firstName = firstName;
this.secondName = secondName;
this.fullName = function() {
console.log(this.firstName + this.secondName); //this should output result of both john.fullName() and will.fullName()
}
}
var john = new x("John ", "Smith");
var will = new x("Will ", "Adams");
</script>
这是如何在javascript中完成的?优选地,它将没有指定实例的数量,而是仅针对已经创建的所有实例运行该方法。提前谢谢。
答案 0 :(得分:2)
这是可能的,但请注意,创建的任何x
都不会被垃圾回收
最初我有以下代码
var x = (function() {
var objs = [];
var x = function x(firstName, secondName) {
this.firstName = firstName;
this.secondName = secondName;
objs.push(this);
this.fullName = function() {
objs.forEach(function(obj) {
console.log(obj.firstName + obj.secondName); //this should output result of both john.fullName() and will.fullName()
});
};
};
})();
var john = new x("John ", "Smith");
var will = new x("Will ", "Adams");
will.fullName();
然而,我想到了它,并认为这更有意义
var x = (function() {
var objs = [];
var x = function x(firstName, secondName) {
this.firstName = firstName;
this.secondName = secondName;
objs.push(this);
this.fullName = function() {
console.log(this.firstName + this.secondName); //this should output result of both john.fullName() and will.fullName()
};
};
x.fullName = function() {
objs.forEach(function(obj) {
obj.fullName();
});
}
return x;
})();
var john = new x("John ", "Smith");
var will = new x("Will ", "Adams");
x.fullName();