We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

번역 작업 진행중입니다.

Object.setPrototypeOf() 메소드는  지정된 객체의 프로토타입 (즉, 내부 [[Prototype]] 프로퍼티)을 다른 객체 또는 null 로 설정합니다.

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

Syntax

Object.setPrototypeOf(obj, prototype);

Parameters

obj
프로토타입을 설정을 가지는 객체
prototype
객체의 새로운 프로토 타입  (객체 or null).

Return value

지정된 객체 

Description

만일 프로토타입이 변경될 객체가 Object.isExtensible() 에 의해서 non-extensible 하다면,  TypeError 예외처리를 해라. 만일 프로토타입 파라미터가 객체가 아니거나 null (i.e., number, string, boolean,  undefined) 인 경우가 아니라면 어떠한 작업도 하지마라. 이 방법을 통해서 객제의 프로토타입이 새로운 값으로 변경될 것이다.

Object.setPrototypeOf는 ECMAScript 2015 스펙으로 규정되어 있다. 해당 메소드는 일반적으로 객체의 프로토타입과 논쟁이 되는 Object.prototype.__proto__ 프로퍼티를 설정하는 적절한 방법으로 고려된다. 

Examples

var dict = Object.setPrototypeOf({}, null);

Polyfill

예전 버전의 프로퍼티 Object.prototype.__proto__ 를 사용한다면, 우리는 쉽게 Object.setPrototypeOf 가 쉽게 정의 할수 있다.

// Only works in Chrome and FireFox, does not work in IE:
Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
  obj.__proto__ = proto;
  return obj; 
}

Appending Prototype Chains

Object.getPrototypeOf() and Object.prototype.__proto__ 의 결합은 새로운 프로토타입 오브젝트에 전반적인 프로토타입 Chain을 설정하도록 할수 있다.

/**
*** Object.appendChain(@object, @prototype)
*
* Appends the first non-native prototype of a chain to a new prototype.
* Returns @object (if it was a primitive value it will transformed into an object).
*
*** Object.appendChain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body")
*** Object.appendChain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body")
*
* Appends the first non-native prototype of a chain to the native Function.prototype object, then appends a
* new Function(["@arg"(s)], "@function_body") to that chain.
* Returns the function.
*
**/

Object.appendChain = function(oChain, oProto) {
  if (arguments.length < 2) { 
    throw new TypeError('Object.appendChain - Not enough arguments');
  }
  if (typeof oProto !== 'object' && typeof oProto !== 'string') {
    throw new TypeError('second argument to Object.appendChain must be an object or a string');
  }

  var oNewProto = oProto,
      oReturn = o2nd = oLast = oChain instanceof this ? oChain : new oChain.constructor(oChain);

  for (var o1st = this.getPrototypeOf(o2nd);
    o1st !== Object.prototype && o1st !== Function.prototype;
    o1st = this.getPrototypeOf(o2nd)
  ) {
    o2nd = o1st;
  }

  if (oProto.constructor === String) {
    oNewProto = Function.prototype;
    oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1));
    this.setPrototypeOf(oReturn, oLast);
  }

  this.setPrototypeOf(o2nd, oNewProto);
  return oReturn;
}

Usage

First example: 프로토타입에 Chain 설정하기

function Mammal() {
  this.isMammal = 'yes';
}

function MammalSpecies(sMammalSpecies) {
  this.species = sMammalSpecies;
}

MammalSpecies.prototype = new Mammal();
MammalSpecies.prototype.constructor = MammalSpecies;

var oCat = new MammalSpecies('Felis');

console.log(oCat.isMammal); // 'yes'

function Animal() {
  this.breathing = 'yes';
}

Object.appendChain(oCat, new Animal());

console.log(oCat.breathing); // 'yes'

Second example: 객체 Contructor의 인스턴스에 존재하는 원래 값을 변경 및 해당 객체 프로토타입에 Chain 설정하기

function MySymbol() {
  this.isSymbol = 'yes';
}

var nPrime = 17;

console.log(typeof nPrime); // 'number'

var oPrime = Object.appendChain(nPrime, new MySymbol());

console.log(oPrime); // '17'
console.log(oPrime.isSymbol); // 'yes'
console.log(typeof oPrime); // 'object'

Third example: Function.prototype객체에 Chain을 설정하고 그 Chain에 새로운 함수를 설정하기

function Person(sName) {
  this.identity = sName;
}

var george = Object.appendChain(new Person('George'),
                                'console.log("Hello guys!!");');

console.log(george.identity); // 'George'
george(); // 'Hello guys!!'

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.setProtoypeOf' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Object.setProtoypeOf' in that specification.
Draft  

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 34 31 (31) 11 (Yes) 9

 

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support No support No support 31.0 (31) ? No support 9

See also

문서 태그 및 공헌자

이 페이지의 공헌자: DevJang, kingsae1
최종 변경: DevJang,