2017-01-17 4 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> 

을 달성하는 방법? 바람직하게는 인스턴스 수를 지정하지 않고 생성 된 모든 인스턴스에 대해 메소드를 실행하는 것입니다. 미리 감사드립니다.

+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

고맙습니다 잘 대답했다. –

관련 문제