前端er

《Understanding ES6》

2017-05-24  本文已影响0人  凛子哥
/* I often use it like this  >.< */
var Person = (function() {

    var privateData = {},
        privateId = 0;

    function Person(name) {
        Object.defineProperty(this, "_id", { value: privateId++ });

        privateData[this._id] = {
            name: name
        };
    }

    Person.prototype.getName = function() {
        return privateData[this._id].name;
    };

    return Person;
}());

/*
This example wraps the definition of `Person` 
in an IIFE that contains two private variables, 
`privateData` and `privateId`.

The big problem with this approach is that the 
data in `privateData` never disappears because 
there is no way to know when an object instance
is destroyed; the `privateData` object will always
contain extra data. This problem can be solved
by using a weak map instead, as follows:
*/

let Person = (function() {

    let privateData = new WeakMap();

    function Person(name) {
        privateData.set(this, { name: name });
    }

    Person.prototype.getName = function() {
        return privateData.get(this).name;
    };

    return Person;
}());

/*
This version of the `Person` example uses a weak map
for the private data instead of an object. Because the
`Person` object instance itself can be used as a key, 
there's no need to keep track of a separate `ID`. When
the `Person` constructor is called, a new entry is made
into the weak map with a key of this and a value of an
object containing private information. 
*/
Proxy Trap Overrides the Behavior Of Default Behavior
get Reading a property value Reflect.get()
set Writing to a property Reflect.set()
has The in operator Reflect.has()
deleteProperty The delete operator Reflect.deleteProperty()
getPrototypeOf Object.getPrototypeOf() Reflect.getPrototypeOf()
setPrototypeOf Object.setPrototypeOf() Reflect.setPrototypeOf()
isExtensible Object.isExtensible() Reflect.isExtensible()
preventExtensions Object.preventExtensions() Reflect.preventExtensions()
getOwnPropertyDescriptor Object.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor()
defineProperty Object.defineProperty() Reflect.defineProperty
ownKeys Object.keys, Object.getOwnPropertyNames(), Object.getOwnPropertySymbols() Reflect.ownKeys()
apply Calling a function Reflect.apply()
construct Calling a function with new Reflect.construct()
上一篇 下一篇

猜你喜欢

热点阅读