JS创建对象的方式

1.函数模拟类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function Box() {
//公开属性使用this来声明
this.name = "mike"; //重点是this
this.sex = "male";
this.age = 12;
this.fun = function() {
console.log("hello");
}

//不使用this的就是私有属性或方法。
var ivar = "ivar";
}
Box.prototype.protofunc = function(first_argument) {
console.log(first_argument);
};
Box.prototype.protovar = "hi,protovar";

var obj1 = new Box();
console.log(obj1.name);
console.log(obj1.sex);
console.log(obj1.age);
obj1.fun();
console.log(obj1.ivar); //私有属性,不可见
obj1.protofunc("hi,proto");
console.log(obj1.protovar);

/*output:
mike
male
12
hello
undefined
hi,proto
hi,protovar
*/

2.Object create,对象模拟类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var Cox = {
name: "mike",
sex: "male",
age: 12,
fun: function() {
console.log("hello");
}
}

var obj2 = Object.create(Cox);
console.log(obj2.name);
console.log(obj2.sex);
console.log(obj2.age);
obj2.fun();

/*output:
mike
male
12
hello
*/

3.极简风,推荐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var Dox = {
createNew: function() {
var dox = {};
var ivar; //私有
dox.name = "hi";
dox.makeSound = function() {
console.log("hello world!")
};
return dox;
}
};

var dox = Dox.createNew();
dox.makeSound();

//3.1 继承
var Doxer = {
createNew : function () {
var doxer = Dox.createNew();//继承
doxer.helloDoxer = "helloDoxer";
return doxer;
}
}
var doxer = Doxer.createNew();
console.log(doxer.helloDoxer);
console.log(doxer.name);

//output:
/*
hello world!
helloDoxer
hi
*/