Programing

자바 스크립트 Object.defineProperty를 사용하는 방법

crosscheck 2020. 5. 29. 07:59
반응형

자바 스크립트 Object.defineProperty를 사용하는 방법


방법을 사용하는 Object.defineProperty방법 을 둘러 보았지만 괜찮은 것을 찾을 수 없었습니다.

누군가 나 에게이 코드 스 니펫을 주었다 .

Object.defineProperty(player, "health", {
    get: function () {
        return 10 + ( player.level * 15 );
    }
})

그러나 나는 그것을 이해하지 못한다. 주로, get내가 얻을 수없는 것입니다. 어떻게 작동합니까?


당신이 질문 때문에 비슷한 질문을 ,의 단계에 의해 단계를 보자. 조금 더 길지만 이것을 쓰는 데 소비 한 시간보다 훨씬 많은 시간을 절약 할 수 있습니다.

속성 은 클라이언트 코드를 깔끔하게 분리하도록 설계된 OOP 기능입니다. 예를 들어 일부 전자 상점에서는 다음과 같은 객체가있을 수 있습니다.

function Product(name,price) {
  this.name = name;
  this.price = price;
  this.discount = 0;
}

var sneakers = new Product("Sneakers",20); // {name:"Sneakers",price:20,discount:0}
var tshirt = new Product("T-shirt",10);  // {name:"T-shirt",price:10,discount:0}

그런 다음 고객 코드 (e-shop)에서 제품에 할인을 추가 할 수 있습니다.

function badProduct(obj) { obj.discount+= 20; ... }
function generalDiscount(obj) { obj.discount+= 10; ... }
function distributorDiscount(obj) { obj.discount+= 15; ... }

나중에 전자 상점 주인은 할인이 80 %를 넘을 수 없다는 것을 깨달을 수 있습니다. 이제 클라이언트 코드에서 할인 수정이 발생할 때마다 찾아서 줄을 추가해야합니다.

if(obj.discount>80) obj.discount = 80;

그런 다음 전자 상점 소유자는 "고객이 리셀러 인 경우 최대 할인은 90 % 일 수 있습니다" 와 같은 전략을 추가로 변경할 수 있습니다 . 그리고 여러 장소에서 변경을 다시 수행해야하며 전략이 변경 될 때마다 이러한 행을 변경해야합니다. 이것은 나쁜 디자인입니다. 이것이 캡슐화 가 OOP의 기본 원칙 인 이유 입니다. 생성자가 다음과 같은 경우 :

function Product(name,price) {
  var _name=name, _price=price, _discount=0;
  this.getName = function() { return _name; }
  this.setName = function(value) { _name = value; }
  this.getPrice = function() { return _price; }
  this.setPrice = function(value) { _price = value; }
  this.getDiscount = function() { return _discount; }
  this.setDiscount = function(value) { _discount = value; } 
}

그런 다음 getDiscount( accessor ) 및 setDiscount( mutator ) 메소드를 변경할 수 있습니다 . 문제는 대부분의 멤버가 공통 변수처럼 행동한다는 것입니다. 할인은 특별한주의가 필요합니다. 그러나 우수한 디자인을 위해서는 코드를 확장 가능하게 유지하기 위해 모든 데이터 멤버를 캡슐화해야합니다. 따라서 아무것도하지 않는 많은 코드를 추가해야합니다. 이것은 또한 나쁜 디자인, 상용구 반 패턴 입니다. 때로는 나중에 필드를 메소드로 리팩터링 할 수 없습니다 (eshop 코드가 커지거나 일부 타사 코드가 이전 버전에 따라 다를 수 있음). 그러나 여전히 악합니다. 그래서 속성이 많은 언어로 도입되었습니다. 원래 코드를 유지하고 할인 멤버를get그리고 set블록 :

function Product(name,price) {
  this.name = name;
  this.price = price;
//this.discount = 0; // <- remove this line and refactor with the code below
  var _discount; // private member
  Object.defineProperty(this,"discount",{
    get: function() { return _discount; },
    set: function(value) { _discount = value; if(_discount>80) _discount = 80; }
  });
}

// the client code
var sneakers = new Product("Sneakers",20);
sneakers.discount = 50; // 50, setter is called
sneakers.discount+= 20; // 70, setter is called
sneakers.discount+= 20; // 80, not 90!
alert(sneakers.discount); // getter is called

마지막 한 줄을 참고하십시오. 올바른 할인 가치에 대한 책임이 고객 코드 (e-shop 정의)에서 제품 정의로 이동되었습니다. 제품은 데이터 멤버의 일관성을 유지해야합니다. 코드가 우리의 생각과 같은 방식으로 작동한다면 좋은 디자인입니다.

속성에 대해 너무 많은. 그러나 javascript는 C #과 같은 순수한 객체 지향 언어와 다르며 기능을 다르게 코딩합니다.

C # 에서 필드를 속성으로 변환하는 것은 중요한 변경 사항 이므로 코드를 별도로 컴파일 된 클라이언트에서 사용할 수있는 경우 공용 필드를 자동 구현 속성 으로 코딩해야합니다 .

Javascript 에서 표준 속성 (위에 설명 된 getter 및 setter가있는 데이터 멤버)은 접근 자 설명자 (질문에있는 링크에서 )로 정의됩니다 . 전용, 당신이 사용할 수있는 데이터 기술자를 (당신이 예를 사용할 수 있도록 설정을 동일한 속성에) :

  • 접근 자 설명자 = get + set (위 예 참조)
    • get 은 함수 여야합니다. 반환 값은 속성을 읽는 데 사용됩니다. 지정하지 않으면 기본값은 undefined 이며 undefined 를 반환하는 함수처럼 동작합니다
    • set 은 함수 여야합니다. 속성에 값을 할당 할 때 RHS로 매개 변수가 채워집니다. 지정하지 않으면 기본값은 undefined 이며 빈 함수처럼 작동합니다.
  • 데이터 디스크립터 = 값 + 쓰기 가능 (아래 예 참조)
    • 기본값 undefined ; 쓰기 가능 , 구성 가능 열거 가능 (아래 참조)이 true 인경우이속성은 일반 데이터 필드처럼 동작합니다
    • 쓰기 가능 -기본값 false ; true 가 아닌 경우 속성은 읽기 전용입니다. 쓰기 시도는 오류 *없이 무시됩니다!

두 디스크립터 모두 다음 멤버를 가질 수 있습니다.

  • 구성 가능 -기본값 false ; true가 아닌 경우 속성을 삭제할 수 없습니다. 삭제 시도는 오류없이 무시됩니다 *!
  • 열거 가능 -기본값은 false입니다 . 참이면 반복됩니다for(var i in theObject). false 인 경우 반복되지 않지만 여전히 공용으로 액세스 할 수 있습니다.

*에 않는 엄격 모드 -가에 걸렸 않는 경우에 JS는 형식 오류와 실행을 중지 시도 캐치 블록

이 설정을 읽으려면을 사용하십시오 Object.getOwnPropertyDescriptor().

예를 들어 배우십시오 :

var o = {};
Object.defineProperty(o,"test",{
  value: "a",
  configurable: true
});
console.log(Object.getOwnPropertyDescriptor(o,"test")); // check the settings    

for(var i in o) console.log(o[i]); // nothing, o.test is not enumerable
console.log(o.test); // "a"
o.test = "b"; // o.test is still "a", (is not writable, no error)
delete(o.test); // bye bye, o.test (was configurable)
o.test = "b"; // o.test is "b"
for(var i in o) console.log(o[i]); // "b", default fields are enumerable

클라이언트 코드와 같은 치트를 허용하지 않으려면 세 가지 수준의 제한으로 개체를 제한 할 수 있습니다.

  • Object.preventExtensions (yourObject) 는 새 속성이 yourObject에 추가되지 않도록 합니다. 사용Object.isExtensible(<yourObject>)방법은 개체에 사용 된 경우 확인합니다. 예방은 얕습니다 (아래 참조).
  • Object.seal (yourObject) 은 위와 동일하며 속성을 제거 할 수 없습니다 (효과적으로configurable: false모든 속성으로설정). Object.isSealed(<yourObject>)객체에서이 기능을 감지하는 데사용합니다. 씰이 얕습니다 (아래 참조).
  • Object.freeze (yourObject) 는 위와 동일하며 속성을 변경할 수 없습니다 (writable: false데이터 설명자를 사용하여 모든 속성으로효과적으로 설정). 세터의 쓰기 가능 속성은 영향을받지 않습니다 (속성이 없기 때문에). 동결은 얕습니다 . 즉, 속성이 Object 인 경우 속성이 고정되지 않습니다 (원하는 경우 딥 카피 복제 와 유사한 "깊은 고정"과 같은 작업을 수행해야 함). Object.isFrozen(<yourObject>)감지하는 데사용하십시오.

몇 줄의 재미 만 쓰면 이것을 귀찮게 할 필요가 없습니다. 그러나 게임을 코딩하려면 (관련 질문에서 언급 한 바와 같이) 좋은 디자인에 관심을 가져야합니다. 반 패턴코드 냄새 에 대해 Google에 무언가를 시도하십시오 . "아, 코드를 완전히 다시 작성해야합니다!" 와 같은 상황을 피하는 데 도움이 됩니다. 코드를 많이 작성하려는 경우 몇 개월 동안 절망 할 수 있습니다. 행운을 빕니다.


get다음 player.health과 같이 value를 읽으려고 할 때 호출되는 함수입니다 .

console.log(player.health);

실제로 다음과 크게 다르지 않습니다.

player.getHealth = function(){
  return 10 + this.level*15;
}
console.log(player.getHealth());

get의 반대가 설정되어 값을 지정할 때 사용됩니다. 세터가 없기 때문에 플레이어의 건강에 할당하는 것은 의도되지 않은 것 같습니다.

player.health = 5; // Doesn't do anything, since there is no set function defined

매우 간단한 예 :

var player = {
  level: 5
};

Object.defineProperty(player, "health", {
  get: function() {
    return 10 + (player.level * 15);
  }
});

console.log(player.health); // 85
player.level++;
console.log(player.health); // 100

player.health = 5; // Does nothing
console.log(player.health); // 100


defineProperty 는 일부 기준을 충족하도록 특성을 구성 할 수있는 Object의 메소드입니다. 다음은 firstName 및 lastName이라는 두 가지 속성을 가진 직원 개체를 사용하는 간단한 예제이며 개체에서 toString 메서드를 재정 의하여 두 속성을 추가 합니다.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
employee.toString=function () {
    return this.firstName + " " + this.lastName;
};
console.log(employee.toString());

다음과 같이 출력됩니다. Jameel Moideen

객체에서 defineProperty를 사용하여 동일한 코드를 변경하려고합니다.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: true,
    enumerable: true,
    configurable: true
});
console.log(employee.toString());

첫 번째 매개 변수는 객체의 이름이고 두 번째 매개 변수는 우리가 추가하는 속성의 이름입니다.이 경우 toString이고 마지막 매개 변수는 json 객체이며 값은 함수가되고 3 개의 매개 변수는 쓰기 가능하고 열거 가능합니다. 지금은 모든 것을 사실로 선언했습니다.

예제를 실행하면 다음과 같이 출력됩니다. Jameel Moideen

쓰기 가능, 열거 가능 및 구성 가능과 같은 세 가지 속성이 왜 필요한지 이해하겠습니다 .

쓰기 가능

예를 들어 toString 속성을 다른 것으로 변경하면 자바 스크립트의 매우 성가신 부분 중 하나는입니다.

여기에 이미지 설명을 입력하십시오

다시 실행하면 모든 것이 중단됩니다. 쓰기 가능을 false로 변경합시다. 다시 동일하게 실행하면 'Jameel Moideen'과 같은 올바른 출력이 표시됩니다. 이 속성은 나중에이 속성을 덮어 쓰지 못하게합니다.

열거 할 수있는

객체 내부의 모든 키를 인쇄하면 toString을 포함한 모든 속성을 볼 수 있습니다.

console.log(Object.keys(employee));

여기에 이미지 설명을 입력하십시오

열거 형을 false로 설정하면 다른 모든 사람에게 toString 속성을 숨길 수 있습니다. 이것을 다시 실행하면 firstName, lastName이 표시됩니다.

구성 가능

나중에 누군가가 나중에 객체를 재정 의하여 예를 들어 true로 열거하고 실행하는 경우. toString 속성이 다시 온 것을 볼 수 있습니다.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: false,
    enumerable: false,
    configurable: true
});

//change enumerable to false
Object.defineProperty(employee, 'toString', {

    enumerable: true
});
employee.toString="changed";
console.log(Object.keys(employee));

여기에 이미지 설명을 입력하십시오

configurable을 false로 설정하여이 동작을 제한 할 수 있습니다.

이 정보의 원래 참조는 내 개인 블로그에서 가져온 것입니다


기본적으로 defineProperty객체, 속성 및 설명 자라는 3 개의 매개 변수를 사용하는 방법입니다. 이 특정 호출에서 일어나는 "health"것은 player객체 속성 이 플레이어 객체 레벨의 10 + 15 배에 할당되고 있다는 것입니다.


설치 세터 &에 대한 확장 많은 기능을 예 아니오 게터이 내 예입니다 Object.defineProperty (OBJ, 이름, FUNC)

var obj = {};
['data', 'name'].forEach(function(name) {
    Object.defineProperty(obj, name, {
        get : function() {
            return 'setter & getter';
        }
    });
});


console.log(obj.data);
console.log(obj.name);

Object.defineProperty ()는 전역 함수입니다 .. 그렇지 않으면 개체를 다르게 선언하는 함수 내에서 사용할 수 없습니다. 정적으로 사용해야합니다.


요약:

Object.defineProperty(player, "health", {
    get: function () {
        return 10 + ( player.level * 15 );
    }
});

Object.defineProperty is used in order to make a new property on the player object. Object.defineProperty is a function which is natively present in the JS runtime environemnt and takes the following arguments:

Object.defineProperty(obj, prop, descriptor)

  1. The object on which we want to define a new property
  2. The name of the new property we want to define
  3. descriptor object

The descriptor object is the interesting part. In here we can define the following things:

  1. configurable <boolean>: If true the property descriptor may be changed and the property may be deleted from the object. If configurable is false the descriptor properties which are passed in Object.defineProperty cannot be changed.
  2. Writable <boolean>: If true the property may be overwritten using the assignment operator.
  3. Enumerable <boolean>: If true the property can be iterated over in a for...in loop. Also when using the Object.keys function the key will be present. If the property is false they will not be iterated over using a for..in loop and not show up when using Object.keys.
  4. get <function> : A function which is called whenever is the property is required. Instead of giving the direct value this function is called and the returned value is given as the value of the property
  5. set <function> : A function which is called whenever is the property is assigned. Instead of setting the direct value this function is called and the returned value is used to set the value of the property.

Example:

const player = {
  level: 10
};

Object.defineProperty(player, "health", {
  configurable: true,
  enumerable: false,
  get: function() {
    console.log('Inside the get function');
    return 10 + (player.level * 15);
  }
});

console.log(player.health);
// the get function is called and the return value is returned as a value

for (let prop in player) {
  console.log(prop);
  // only prop is logged here, health is not logged because is not an iterable property.
  // This is because we set the enumerable to false when defining the property
}


import { CSSProperties } from 'react'
import { BLACK, BLUE, GREY_DARK, WHITE } from '../colours'

export const COLOR_ACCENT = BLUE
export const COLOR_DEFAULT = BLACK
export const FAMILY = "'Segoe UI', sans-serif"
export const SIZE_LARGE = '26px'
export const SIZE_MEDIUM = '20px'
export const WEIGHT = 400

type Font = {
  color: string,
  size: string,
  accent: Font,
  default: Font,
  light: Font,
  neutral: Font,
  xsmall: Font,
  small: Font,
  medium: Font,
  large: Font,
  xlarge: Font,
  xxlarge: Font
} & (() => CSSProperties)

function font (this: Font): CSSProperties {
  const css = {
    color: this.color,
    fontFamily: FAMILY,
    fontSize: this.size,
    fontWeight: WEIGHT
  }
  delete this.color
  delete this.size
  return css
}

const dp = (type: 'color' | 'size', name: string, value: string) => {
  Object.defineProperty(font, name, { get () {
    this[type] = value
    return this
  }})
}

dp('color', 'accent', COLOR_ACCENT)
dp('color', 'default', COLOR_DEFAULT)
dp('color', 'light', COLOR_LIGHT)
dp('color', 'neutral', COLOR_NEUTRAL)
dp('size', 'xsmall', SIZE_XSMALL)
dp('size', 'small', SIZE_SMALL)
dp('size', 'medium', SIZE_MEDIUM)

export default font as Font


Defines a new property directly on an object, or modifies an existing property on an object, and return the object.

참고 :이 메소드는 Object 유형의 인스턴스가 아닌 Object 생성자에서 직접 호출합니다.

   const object1 = {};
   Object.defineProperty(object1, 'property1', {
      value: 42,
      writable: true,
      enumerable: true,
      configurable: true
   });

여기에 이미지 설명을 입력하십시오

속성 정의에 대한 간단한 설명.

참고 URL : https://stackoverflow.com/questions/18524652/how-to-use-javascript-object-defineproperty

반응형