Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 新增基本数据类型--Symbol #10

Open
chenwangji opened this issue Jun 24, 2019 · 0 comments
Open

ES6 新增基本数据类型--Symbol #10

chenwangji opened this issue Jun 24, 2019 · 0 comments
Milestone

Comments

@chenwangji
Copy link
Owner

Symbol 的作用

对象属性私有化

如果没有 Symbol,可以这样实现,

利用闭包:

var Person = (function () {
    var _gender = '';
    var P = function (name, gender) {
        this.name = name;
        _gender = gender;
    }
    P.prototype.getGender = function () {
        return _gender;
    }
    return P
})()

var p1 = new Person('小明', '男');
p1.gender // undefined
p1.getGender() // '男'

使用 Symbol, 具体代码:

var Person = (function () {
    var s = Symbol('gender');
    var P = function(name, gender) {
        this.name = name;
        this[s] = gender;
    }
    return P
})()
var p2 = new Person('小明', '男');
p2.gender // undefined
p2[Symbol('gender')] // undefined
@chenwangji chenwangji added this to the 笔记本 milestone Jun 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant