UFO ET IT

ES6 객체의 방법 : 화살표 기능 사용

ufoet 2020. 11. 14. 11:24
반응형

ES6 객체의 방법 : 화살표 기능 사용


ES6에서는 두 가지 모두 합법적입니다.

var chopper = {
    owner: 'Zed',
    getOwner: function() { return this.owner; }
};

그리고 속기 :

var chopper = {
    owner: 'Zed',
    getOwner() { return this.owner; }
}

새로운 화살표 기능도 사용할 수 있습니까? 같은 시도에서

var chopper = {
    owner: 'John',
    getOwner: () => { return this.owner; }
};

또는

var chopper = {
    owner: 'John',
    getOwner: () => (this.owner)
};

메서드에에 대한 액세스 권한이 없다는 오류 메시지가 나타납니다 this. 이것은 단지 구문 문제입니까, 아니면 ES6 객체 내에서 fat-pipe 메서드를 사용할 수 없습니까?


Arrow 함수는 모든 상황에서 구식 함수의 더 짧은 버전으로 사용되도록 설계되지 않았습니다. function키워드를 사용하여 함수 구문을 대체하기위한 것이 아닙니다 . 화살표 함수의 가장 일반적인 사용 사례는 재정의하지 않는 짧은 '람다' this로, 일부 함수에 대한 콜백으로 함수를 전달할 때 자주 사용됩니다.

화살표 함수는 this어휘 적으로 둘러싸는 컨텍스트에서 닫히기 때문에 화살표 함수를 사용하여 개체 메서드를 작성할 수 없습니다 this. 즉,

// Whatever `this` is here...
var chopper = {
    owner: 'Zed',
    getOwner: () => {
        return this.owner;    // ...is what `this` is here.
    }
};

귀하의 경우 객체에 대한 메소드를 작성하려면 기존 function구문 또는 ES6에 도입 된 메소드 구문을 사용해야 합니다.

var chopper = {
    owner: 'Zed',
    getOwner: function() {
        return this.owner;
    }
};

// or

var chopper = {
    owner: 'Zed',
    getOwner() {
        return this.owner;
    }
};

(그들 사이에는 작은 차이가 있지만 super에서 사용 getOwner하거나 사용하지 않는 경우 또는 getOwner다른 개체에 복사 하는 경우 에만 중요 합니다.)

There was some debate on the es6 mailing list about a twist on arrow functions which have similar syntax but with their own this. However, this proposal was poorly received because that is mere syntax sugar, allowing people to save typing a few characters, and provides no new functionality over existing function syntax. See the topic unbound arrow functions.


In this line getOwner: => (this.owner) should be:

var chopper = {
    owner: 'John',
    getOwner: () => this.owner
}; //here `this` refers to `window` object.

You would have to declare this into a function:

var chopper = {
    owner: 'John',
    getOwner() { return this.owner }
};

Or:

var chopperFn = function(){

    this.setOwner = (name) => this.owner = name;
    Object.assign(this,{
        owner: 'Jhon',
        getOwner: () => this.owner,
    })

}

var chopper = new chopperFn();
console.log(chopper.getOwner());
chopper.setOwner('Spiderman');
console.log(chopper.getOwner());


This inside arrow function doesn't reflect context of the object. Instead it gives the context where the object method is called.

Check this, This gives some insight about when to use arrow and when not. https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/

참고URL : https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions

반응형