2017-01-17 11 views
0

オブジェクトのすべてのインスタンスに属するメソッドを実行する必要があります。私は.firstNameと.secondNameを連結する方法のfullName()を、持っていた場合たとえば、私は、コード内のオブジェクトの両方のインスタンスのためにそれを行うしたいと思います:オブジェクトのすべてのインスタンスのメソッドを呼び出す方法

<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

[オブジェクトリテラル値の反復]の複製が可能です(http://stackoverflow.com/questions/9354834/iterate-over-object-literal-values) – Hodrobond

+0

は 'this.fullName ='を 'x.prototype.fullName ='と定義し、すぐにどこでも動作します。コンストラクタからもそれを移動してください... – dandavis

+0

[instanceof](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/instanceof)演算子を使用できます – maioman

答えて

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

ありがとうよく考え抜かれた答え。 –

関連する問題