Program Tip

프로토 타입에서 setter / getter를 정의하는 방법

programtip 2020. 10. 25. 12:51
반응형

프로토 타입에서 setter / getter를 정의하는 방법


2016 년 10 월 수정 :이 질문은 2012 년에 요청되었습니다. 매달 누군가가 답변을 반박하는 새로운 답변이나 댓글을 추가하지만 질문이 오래되었을 수 있으므로 그렇게하는 것이 의미가 없습니다. Gnome Javascript브라우저가 아닌 gnome-shell 확장 프로그램을 작성했습니다.

Javascript에서 하위 클래스를 수행하는 방법에 대한 이전 질문따라 다음 과 같이 수퍼 클래스의 하위 클래스를 만들고 있습니다.

function inherits(Child,Parent) {
    var Tmp = function {};
    Tmp.prototype = Parent.prototype;
    Child.prototype = new Tmp();
    Child.prototype.constructor = Child;
}
/* Define subclass */
function Subclass() {
    Superclass.apply(this,arguments);
    /* other initialisation */
}
/* Set up inheritance */
inherits(Subclass,Superclass);
/* Add other methods */
Subclass.prototype.method1 = function ... // and so on.

내 질문은 이 구문을 사용하여 프로토 타입에서 setter / getter를 어떻게 정의합니까?

나는 그것을 하고는했다:

Subclass.prototype = {
    __proto__: Superclass.prototype,
    /* other methods here ... */

    get myProperty() {
        // code.
    }
}

그러나 분명히 다음은 작동하지 않습니다.

Subclass.prototype.get myProperty() { /* code */ }

저는 GJS (GNOME Javascript)를 사용하고 있으며 엔진은 Mozilla Spidermonkey와 거의 동일합니다. 내 코드는 GJS에서 지원하는 한 브라우저 용이 아닙니다 (Spidermonkey를 의미합니까?). 교차 호환이되지 않아도 상관 없습니다.


객체 리터럴 선언 사용 (가장 간단한 방법) :

var o = {
    a: 7,
    get b() {
        return this.a + 1;
    },
    set c(x) {
        this.a = x / 2
    }
};

사용 Object.defineProperty(ES5를 지원하는 최신 브라우저에서) :

Object.defineProperty(o, "myProperty", {
    get: function myProperty() {
        // code
    }
});

또는 __defineGetter__사용 __defineSetter__( DEPRECATED ) :

var d = Date.prototype;
d.__defineGetter__("year", function() { return this.getFullYear(); });
d.__defineSetter__("year", function(y) { this.setFullYear(y); });

사용 Object.defineProperty()Subclass.prototype. 이 또한 __defineGetter____defineSetter__일부 브라우저에서 사용할 수 있지만,이되지 않습니다. 귀하의 예를 들면 다음과 같습니다.

Object.defineProperty(Subclass.prototype, "myProperty", {
    get: function myProperty() {
        // code
    }
});

나는 당신이 이렇게하고 싶었다고 생각합니다.

function Unit() {
   	this._data; // just temp value
}
Unit.prototype = {
 	get accreation() {
   		return this._data;
   	},
   	set accreation(value) {
   		this._data = value
   	},
}
Unit.prototype.edit = function(data) {
   	this.accreation = data; // setting
   	this.out();
};

Unit.prototype.out = function() {
    alert(this.accreation); // getting
};

var unit = new Unit();
unit.edit('setting and getting');

function Field() {
    // children
}

Field.prototype = Object.create(Unit.prototype);

Field.prototype.add = function(data) {
  this.accreation = data; // setting
   	this.out();
}

var field1 = new Field();
field1.add('new value for getter&setter');

var field2 = new Field();
field2.out();// because field2 object has no setting


setter와 getter를 "객체의 프로토 타입 내부에"정의하려면 다음과 같이해야합니다.

Object.defineProperties(obj.__proto__, {"property_name": {get: getfn, set: setfn}})

유틸리티 함수로 단축 할 수 있습니다.

//creates get/set properties inside an object's proto
function prop (propname, getfn, setfn) {
    var obj = {};
    obj[propname] = { get: getfn, set: setfn };
    Object.defineProperties(this, obj);        
}

function Product () {
     this.name =  "Product";
     this.amount =  10;
     this.price =  1;
     this.discount =  0;
}

//how to use prop function
prop.apply(Product.prototype, ["total", function(){ return this.amount * this.price}]);

pr = new Product();
console.log(pr.total);

Here we use prop.apply to set the context Product.prototype as "this" when we call it.

With this code you end with a get/set property inside the object's prototype, not the instance, as the question asked.

(Tested Firefox 42, Chrome 45)


Specify a getter or a setter in constructors by Object.defineProperty() method. This method takes three arguments: the first argument is the object to add the property to, the second is the name of the property, and the third is the property's descriptor. For instance, we can define the constructor for our person object as follows:

var Employee = (function() {
    function EmployeeConstructor() {
        this.first = "";
        this.last = "";
        Object.defineProperty(
            this,
            "fullName", {
                get: function() {
                    return this.first + " " +
                        this.last;
                },
                set: function(value) {
                    var parts = value.toString().split(" ");
                    this.name = parts[0] || "";
                    this.last = parts[1] || "";
                }
            });
    }
    return
    EmployeeConstructor;
}());

Using Object.defineProperty() gives more control over our property definition. For example, we can specify if the property we are describing can be dynamically deleted or redefined, if its value can be changed, and so on.

We can such constraints by setting the following properties of the descriptor object:

  • writable: This is a Boolean that says whether the value of the property can be changed; its default value is false
  • configurable: This is a Boolean that says whether the property's descriptor can be changed or the property itself can be deleted; its default value is false
  • enumerable: This is a Boolean indicating whether the property can be accessed in a loop over the object's properties; its default value is false
  • value: This represents the value associated to the property; its default value is undefined

참고URL : https://stackoverflow.com/questions/10592753/how-to-define-setter-getter-on-prototype

반응형