2013-03-18 3 views
2

다음과 같은 코드가 있다고 가정 해 보겠습니다.Object Literal의 프로토 타입 설정

var A = {a:10}; 
var B = {b:20}; 
B.prototype = A; 
alert(B.a); 

B.a에 대해 정의되지 않았습니다. 내가 잘못하고 있니? 객체 리터럴의 프로토 타입을 어떻게 설정합니까?

저는 Constructor 객체에서하는 방법을 알고 있습니다. 따라서 다음 코드는 완벽합니다.

function A(){this.a=10} 
function B(){this.b=20} 
B.prototype = new A(); 
b = new B; 
alert(b.a); 

개체 리터럴에서는 어떻게합니까?

+0

관련 : http://stackoverflow.com/q/ 7015693/989121 – georg

+0

짧은 대답 : 당신은 할 수 없습니다 – slebetman

+0

가능한 duplicat http://stackoverflow.com/questions/9959727/java-script-what-is-the-difference-between-proto-and-prototype 또는 http://stackoverflow.com/questions/572897/how-does- javascript-prototype-work? lq = 1 또는 http://stackoverflow.com/questions/650764/how-does-proto-differ-from-constructor-prototype?rq=1 또는 http://stackoverflow.com/questions/ 9451881/prototype-vs-prototype-what-is-the-difference-mycons-proto-myco/9451979 # 9451979 –

답변

3

일반적으로 prototype 속성은 Function 개체에 있습니다. 이 프로토 타입은 객체 여야하며,이 객체는 생성자로 생성 된 객체의 속성을 정의하는 데 사용됩니다.

// Plain object, no prototype property here. 
var plainObject = {one: 1, two: 2}; 

// Constructor, a prototype property will be created by default 
var someConstruct = function() { 

    // Constructor property 
    someConstruct.constructProp = "Some value"; 

    // Constructor's prototype method 
    someConstruct.prototype.hello = function() { 
    return "Hello world!"; 
    } 
}; 

// Another constructor's prototype method 
someConstruct.prototype.usefulMethod = function() { 
    return "Useful string"; 
} 

var someInstance = new someConstruct(); 
console.log(someInstance.hello()); // => Hello world! 
console.log(someInstance.usefulMethod()); // => Useful string 

console.log(someConstruct.constructProp); // => Some value 
console.log(someConstruct.prototype); // => {usefulMethod: function, hello: function} 

console.log(plainObject.prototype); // => undefined 

따라서 일반 객체에는 프로토 타입이 없습니다. 생성자로 작동하는 함수에는 프로토 타입이 있습니다. 이 프로토 타입은 각 구문으로 만든 인스턴스를 채우는 데 사용됩니다.

희망하는 데 도움이 :

+1

위의 경우 someConstruct와 같이 프로토 타입에 직접 속성을 정의하는 것의 차이점은 무엇입니까? constructProp Vs someConstruct.prototype.somePrototypeProperty – testndtv

0

를 예를 들면, 프로토 타입을 사용하는 것을 Function 객체를 사용하는 경우에만 생성자를 사용할 때. 그러나 객체 리터럴을위한 필요는 없습니다.

두 가지 모두 매우 좋은 기술이므로 프로젝트 및 자바 스크립트 패턴에서 수행하고자하는 작업에 따라 다릅니다.

10

개체는 자신의 프로토 타입 속성 에서 상속됩니다. 생성자의 프로토 타입은 __proto__ 속성으로 일부 브라우저에서 사용할 수있는 내부 [[Prototype]] 속성에 할당됩니다.

ba에서 상속하려면 ab 상속 체인에 입력해야합니다. 예 :

클래식 프로토 타입 상속 :

var a = {a: 'a'}; 
function B(){} 
B.prototype = a; 

var b = new B(); 
alert(b.a); // a 

ES5 Object.create 사용 :

var a = {a: 'a'}; 
var b = Object.create(a); 

alert(b.a); // a 

모질라 __proto__ 사용 :

var a = {a: 'a'}; 
var b = {}; 
b.__proto__ = a; 

alert(b.a); // a 
+0

ES5 Object.create 예제를 보면'a'가'b' 상속/프로토 타입 체인에 연결되면'a'를 어떻게 늘릴 수 있을까요? –

+0

'a' 속성을 직접적으로 증가시켜야합니다. 'a.foo = 'foo ''.'b'에 지정하면 동일한 이름의 속성이 'a'에 있어도 'b'의 속성이 생성됩니다. – RobG

+0

@RobG "b에 할당"은 "b의 속성"대신 "b"에 속성을 만들 것입니다. – cchamberlain