What are __defineGetter__() and __defineSetter__() functions?

后端 未结 3 884
深忆病人
深忆病人 2020-12-28 14:06

What are __defineGetter__() and __defineSetter__() functions in prototype of every Object?

相关标签:
3条回答
  • 2020-12-28 14:14

    See the MDN docs here for a description and example code:

    A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties.

    As noted in the docs (and by @ cwallenpoole), __define[GS]etter__() functions are now deprecated. There's a lot more detail in this article. I believe the defineProperty() function is now the preferred syntax.

    0 讨论(0)
  • 2020-12-28 14:27

    To answer your question __defineGetter__() and __defineSetter__() are the old/original way to create a getter and a setter for an object's property. They allow you use an object's property as a name/value pair while behind the scenes these name/value pairs are supported by functions.

    For example, let's say you wanted to reference some random numbers in fixed ranges. You could express these as words with the maximum of the range and it would look like a property.

    var random = {};
    random.__defineGetter__('ten', function() { 
        return Math.floor(Math.random()*10); });
    random.__defineGetter__('hundred', function() { 
        return Math.floor(Math.random()*100); });
    

    Note that the while the above example answers the question you should not use this solution. Instead you should use the modern form of getters and setters since ES5:

    var random = {
        get ten() { return Math.floor(Math.random()*10); },
        get hundred() { return Math.floor(Math.random()*100); }
    };
    

    Either of the above constructs would allow you to get a random number like this:

    var myrand = random.ten;
    // returns a result in the range 0 to 9
    
    0 讨论(0)
  • 2020-12-28 14:33

    .__defineGetter__ it means when you refer to object.[param1] a function executed. .__defineSetter__ it means when you set object.[param1] a function executed. for example, like this:

    const person = {
      firstName: 'john',
      lastName: 'doe',
    };
    
    person.__defineGetter__('fullName', () => `${person.firstName} ${person.lastName}`);
    person.__defineSetter__('fullName', v => {
      person.firstName = v.split(' ')[0];
      person.lastName = v.split(' ')[1];
    });
    

    or if you want cls to clear the console,

    this.__defineGetter__('cls', console.clear);
    
    0 讨论(0)
提交回复
热议问题