2009-11-17 1 views

답변

2

비 기본 객체를 this.somevar 또는 prototype.somevar에 할당하는 경우에는 최소한 차이점이 있습니다.

실행 해보십시오이 : 나는 시도

function Agent(bIsSecret) 
{ 
    if(bIsSecret) 
     this.isSecret=true; 

    this.isActive = true; 
    this.isMale = false; 
    this.myArray = new Array(1,2,3); 
} 

function Agent2(bIsSecret) 
{ 
    if(bIsSecret) 
     this.isSecret = true; 
} 

Agent2.prototype.isActive = true;  
Agent2.prototype.isMale = true; 
Agent2.prototype.myArray = new Array(1,2,3); 

var agent_a = new Agent(); 
var agent_b = new Agent(); 

var agent2_a = new Agent2(); 
var agent2_b = new Agent2(); 

if (agent_a.myArray == agent_b.myArray) 
    alert('agent_a.myArray == agent_b.myArray'); 
else 
    alert('agent_a.myArray != agent_b.myArray'); 

if (agent2_a.myArray == agent2_b.myArray) 
    alert('agent2_a.myArray == agent2_b.myArray'); 
else 
    alert('agent2_a.myArray != agent2_b.myArray'); 
+0

: agent_a.myArray = agent_b.myArray ' agent2_a.myArray == agent2_b.myArray 그래서, 그것은 보여줍니다에서 "이을 사용하여! "각 객체에는 고유 한 속성, 기능이 있습니다. 하지만 프로토 타입을 사용하면 공유됩니다. 하나의 객체에서 배열을 변경하면 다른 객체에서도 배열이 변경되므로 문제가 될 수 있습니다. :( – pencilCake

+0

옙, 그런 것;) – Lukman

1

제 '프로토 타입'. 것과 같은 :

/** obsolete syntax **/ 

var Person = Class.create(); 
Person.prototype = { 
    initialize: function(name) { 
    this.name = name; 
    }, 
    say: function(message) { 
    return this.name + ': ' + message; 
    } 
}; 

var guy = new Person('Miro'); 
guy.say('hi'); 
// -> "Miro: hi" 

var Pirate = Class.create(); 
// inherit from Person class: 
Pirate.prototype = Object.extend(new Person(), { 
    // redefine the speak method 
    say: function(message) { 
    return this.name + ': ' + message + ', yarr!'; 
    } 
}); 

var john = new Pirate('Long John'); 
john.say('ahoy matey'); 
// -> "Long John: ahoy matey, yarr!" 

코드 소스 및 추가 정보를 원하시면 여기 찾을 수 있습니다 http://www.prototypejs.org/learn/class-inheritance

0

기능적으로,이 동일합니다. 그러나 후자는 Agent 개체 간의 유사점을 강조합니다. 이 멤버들은 그 값을 가지고있는 것을 볼 수 있습니다. 반면에 더 복잡한 생성자 함수에서는 많은 조건문을 사용하는 것이 더 어렵습니다.

또한 자바 스크립트 런타임에서 Agent 멤버 초기화를 처리하는 방법을 선택할 수 있습니다. (일부 사전 컴파일 ...)

0

이 함수가 생성자로 사용된다고 가정하면 첫 번째 인스턴스는 새 인스턴스에서 설정되고 두 번째 인스턴스는 프로토 타입에서 설정됩니다. 인스턴스와 독립적 인 경우 두 스 니펫은 동일하지만 이름이 제안하는대로 그렇지 않은 경우 스 니펫이 아닙니다.

관련 문제