0

I need to run a method belonging to all instances of an object. For example, if I had the method fullName(), which concatenates .firstName and .secondName, I would like to do it for both instances of the object in the code:

<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>

How is this accomplished in javascript? Preferably, it would be without specifying the number of instances, and instead just running the method for all instances that have been created. Thanks in advance.

Maxim Webb
  • 67
  • 8
  • Possible duplicate of [Iterate over Object Literal Values](http://stackoverflow.com/questions/9354834/iterate-over-object-literal-values) – Hodrobond Jan 17 '17 at 21:48
  • define `this.fullName=` as `x.prototype.fullName=` and it will instantly work everywhere. move it out of the constructor too... – dandavis Jan 17 '17 at 21:49
  • there is a [instanceof](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/instanceof) operator you can use – maioman Jan 17 '17 at 21:54

1 Answers1

2

It's possible, but be aware that any x created will never be garbage collected

Originally I had the following code

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();

however, I thought about it and think this makes more sense

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();
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87