Skip to content

Commit 462fde4

Browse files
authored
Create 类的封装与实例化.md
1 parent 1a785d6 commit 462fde4

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# JavaScript 类的封装与实例化
2+
3+
JavaScript 是强大的面向对象的编程语言,不过不同于很多传统的编程语言,JavaScript 使用了基于原型链的 OOP 模型;同时,JavaScript 将函数也视作一等对象,也导致了很多开发者可能陷入迷惑。而在面向对象的学习中,我们会考虑命名空间、类的声明、构造函数、对象实例化、类继承等内容。
4+
5+
# 传统的类实现
6+
7+
## 命名空间
8+
9+
面向对象编程的一大特性就是类的封装性,能够避免来自全局命名空间的冲突;在传统的类实现中,我们常用命名空间的模式来进行类封装,[Essential JavaScript Namespacing Patterns](https://addyosmani.com/blog/essential-js-namespacing/#beginners) 一文中 AddyOsmani 就为我们详细介绍了多种 JavaScript 命名空间模式。最简单的嵌套命名空间范式就是使用 Object Literal 来将函数、变量打包到某个唯一的命名下:
10+
11+
```js
12+
MyApp.users = {
13+
// properties
14+
existingUsers: [...],
15+
// methods
16+
renderUsersHTML: function() {
17+
...
18+
}
19+
};
20+
```
21+
22+
## 构造函数
23+
24+
```js
25+
function User( name, email ) {
26+
// properties
27+
this.name = name;
28+
this.email = email;
29+
// methods
30+
this.sayHey = function() {
31+
console.log( “Hey, I’m “ + this.name );
32+
};
33+
}
34+
// instantiating the object
35+
var steve = new User( “Steve”, “steve@hotmail.com” );
36+
// accessing methods and properties
37+
steve.sayHey();
38+
```
39+
40+
41+
42+
# ES6 Class

0 commit comments

Comments
 (0)