类的封装与实例化
JavaScript 类的封装与实例化
传统的类实现
命名空间
面向对象编程的一大特性就是类的封装性,能够避免来自全局命名空间的冲突;在传统的类实现中,我们常用命名空间的模式来进行类封装,Essential JavaScript Namespacing Patterns 一文中
MyApp.users = {
// properties
existingUsers: [...],
// methods
renderUsersHTML: function() {
...
}
};
构造函数
function User( name, email ) {
// properties
this.name = name;
this.email = email;
// methods
this.sayHey = function() {
console.log( “Hey, I’m “ + this.name );
};
}
// instantiating the object
const steve = new User( “Steve”, “steve@hotmail.com” );
// accessing methods and properties
steve.sayHey();