2010-06-20 4 views
14

어떻게 Object.create()를 상속합니까? 나는이 시도했지만 아무도가 작동하지 않습니다 : Object.create()를 사용한 JavaScript 상속?

var B = function() {}; 
A = Object.create(B); 
var A = function() {}; 
A.prototype.C = function() {}; 

아무것도 일하지

var B = function() {}; 
var A = function() {}; 
A = Object.create(B); 
A.prototype.C = function() {}; 

var B = function() {}; 
var A = function() {}; 
A.prototype.C = function() {}; 
A = Object.create(B); 

을. 이 새로운 Object.create() - 함수를 어떻게 사용해야합니까?

+0

중복 가능성 (http://stackoverflow.com/questions/2709612/using-object-create-instead-of-new) – Bergi

답변

21

Object.create()은 사용자가하려는 것처럼 생성자가 아니라 개체를 상속하는 데 사용됩니다. 그것은 꽤 오래된 객체가 prototypal 부모로 설정된 새로운 객체를 생성합니다. 당신은 모질라 개발 센터에 유용한 정보에 대한 JavaScript inheritance를 찾을 수 있습니다

a.x = 'goodbye'; 
delete b.x; 
b.say(); //alerts 'goodbye' 
+0

젠장, 그럼 내 상황에 맞지 않아. 다른 "클래스"를 확장하는 "클래스"를 정의해야합니다. – Tower

+0

프로토 타입 상속의 핵심은 클래스가 객체이기 때문에 "클래스"와 "객체"를 구분하지 않는다는 것입니다. – Kos

+0

'JSON.parse (JSON.stringify (obj)) '와 같은 결과를 생성하는'Object.clone (obj)'가 있었으면 좋겠습니다. – trusktr

0

더글러스의 Object.create에 대한 원래 설명서는 여기에서 http://javascript.crockford.com/prototypal.html입니다. 있는지 확인하십시오 당신은 당신이 Object.create 자신을 정의 할 수 있지만, 네이티브가 아닌 경우는이 루프에서 당신이 개체에 대한 사용을 위해 모든 열거되고 처리해야합니다

if (typeof Object.create !== 'function') { 
    Object.create = function (o) { 
     function F() {} 
     F.prototype = o; 
     return new F(); 
    }; 
} 
+0

.. 해당 구현을 사용하지 않는 것이 좋습니다. http://stackoverflow.com/questions/5199126/javascript-object-create-not-working-in-firefox – zack

0

하여 법의 정의를 포함했다 .

Safari5와 Chrome은 새로운 웹킷 인 Safari5와 Chrome 만 지원합니다.

+3

'Object.create'는'Object'의 속성입니다. 'Object.prototype' 파일의 내용과 일치하지 않으므로 직접 정의하면 모든 객체의 열거 형 속성 목록에 추가되지 않습니다. – kpozin

0

var A = function() { }; 
A.prototype.x = 10; 
A.prototype.say = function() { alert(this.x) }; 

var a = new A(); 
a.say(); //alerts 10 

var b = Object.create(a); 
b.say(); //alerts 10 
b.x = 'hello'; 
b.say(); //alerts 'hello' 

그리고 단지 확인 B는 단지 복제 있지 않은지 확인하기.

나는이에 사용하는 패턴과 같이, 모듈의 각 유형을 포장하고, createprototype 속성을 노출하는 것입니다
16

:

var Vehicle = (function(){ 
     var exports = {}; 
     exports.prototype = {}; 
     exports.prototype.init = function() { 
       this.mph = 5; 
     }; 
     exports.prototype.go = function() { 
       console.log("Going " + this.mph.toString() + " mph."); 
     }; 

     exports.create = function() { 
       var ret = Object.create(exports.prototype); 
       ret.init(); 
       return ret; 
     }; 

     return exports; 
})(); 

가 그럼 난과 같이 파생 된 형식을 구축 할 수 있습니다 :

var Car = (function() { 
     var exports = {}; 
     exports.prototype = Object.create(Vehicle.prototype); 
     exports.prototype.init = function() { 
       Vehicle.prototype.init.apply(this, arguments); 
       this.wheels = 4; 
     }; 

     exports.create = function() { 
       var ret = Object.create(exports.prototype); 
       ret.init(); 
       return ret; 
     }; 

     return exports; 

})(); 

이 패턴의 경우 각 유형마다 고유 한 create() 기능이 있습니다.

+0

추가 정보 : 요즘 클래스와 같은 것을 만들 필요가 있다고 생각하면 Coffeescript를, 그렇지 않은 경우 익명 개체를 사용합니다. –

26

자바 스크립트

건설 상속에 상속을 몇 가지 방법이 있습니다.

function Rectangle(length, width) { 
    this.length = length; 
    this.width = width; 
} 

Rectangle.prototype.getArea = function() { 
    return this.length * this.width; 
}; 

// inherits from Rectangle 
function Square(size) { 
    this.length = size; 
    this.width = size; 
} 

Square.prototype = Object.create(Rectangle.prototype); 

var rect = new Rectangle(6, 8); 
var square = new Square(10); 

console.log(rect.getArea());    // 48 
console.log(square.getArea());    // 100 
console.log(rect instanceof Rectangle);  // true 
console.log(rect instanceof Object);  // true 
console.log(square instanceof Square);  // true 
console.log(square instanceof Rectangle); // true 
console.log(square instanceof Object);  // true 

생성자 도둑질을 : 당신이 슈퍼 생성자를 호출 할 필요가없는 경우에 사용됩니다. 중고 필요가 호출 할 경우 슈퍼 생성자 :

function Rectangle(length, width) { 
    this.length = length; 
    this.width = width; 
} 

Rectangle.prototype.getArea = function() { 
    return this.length * this.width; 
}; 

// inherits from Rectangle 
function Square(size) { 
    Rectangle.call(this, size, size); 
} 

Square.prototype = Object.create(Rectangle.prototype); 

var rect = new Rectangle(6, 8); 
var square = new Square(10); 

console.log(rect.getArea());    // 48 
console.log(square.getArea());    // 100 
console.log(rect instanceof Rectangle);  // true 
console.log(rect instanceof Object);  // true 
console.log(square instanceof Square);  // true 
console.log(square instanceof Rectangle); // true 
console.log(square instanceof Object);  // true 
+0

Square.prototype.constructor = Square를 참조하십시오. 어딘가에, 필요 없어? – c0ming

0

이 잘 늦은 년,하지만이에 걸림돌 다른 사람을 위해. FF와 Chrome에서 Object.assign을 사용할 수 있습니다.

이 예에서는 큐브를 만들 때이 예제를 사용합니다. 최초의 Object.create (this)는 z 속성을 가진 객체를 만든 다음 Object.assign (obj, Square.create (x, y))를 사용하여 Square.create를 호출하고이를 반환하여 obj에 저장되는 큐브에 추가합니다. .[ "Object.create"대신에 "새로운"를 사용]의

var Square = { 
     x: 0, 
     y: 0, 

     create: function(x,y) { 
      var obj = Object.create(this); 
      obj.x = x; 
      obj.y = y; 
      return obj; 
     } 
    }; 

var Cube = { 

     z: 0, 

     create:function(x,y,z) { 
      var obj = Object.create(this); 
      Object.assign(obj, Square.create(x,y)); // assign(target,sources...) 
      obj.z = z; 
      return obj; 
     } 
    }; 

// Your code 
var MyCube = Cube.create(20,30,40); 
console.log(MyCube);