我需要运行属于对象的所有实例的方法。例如,如果我有方法 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 中完成的?优选地,不指定实例的数量,而是仅对已创建的所有实例运行该方法。提前致谢。
最佳答案
这是可能的,但请注意,创建的任何 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();
关于javascript - 如何为对象的所有实例调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707589/