javascript - 如何为对象的所有实例调用方法

标签 javascript oop object methods collections

我需要运行属于对象的所有实例的方法。例如,如果我有方法 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/

相关文章:

javascript - 在联系表单中传递当前页面 URL 和标题

javascript - 如何使用 jquery 进行同步 json ajax 调用

c# - 在 C# 中操作密封类型

c# 是否可以获取对象的引用,获取对象本身并更改它,而不是分配给新对象?

JavaScript 邮件函数 - 从字符串中删除日期戳部分

android - 在实现 Room Database 时,我们为什么可以创建一个 Interface 的对象?

javascript - 使用 javascript 创建一个 asp.net 身份验证 cookie

javascript - jQuery:遍历选择器 ID

封装和抽象 OOP 概念

Java调用类外的函数