1 /*
2 js实现面向对象的方法
3 */
4
5 // 1 工厂模型 不推荐
6 function Person(name , sex , age){
7 obj = {};
8 obj.name = name;
9 obj.sex = sex;
10 obj.age = age;
11 obj.say = function(){
12 alert(this.name +" "+this.sex+" "+this.age);
13 };
14 return obj;
15 }
16
17 var p1 = Person("z3","女",18);
18 p1.say();
19
20
21
22
23 // 2 构造函数方式 推荐
24 // 创建类的时候 第一个字母要大写 这是一种规范
25 function Person(name , sex , age){
26 this.name = name;
27 this.sex = sex;
28 this.age = age;
29 this.say = function(){
30 alert(this.name +" "+this.sex+" "+this.age);
31 };
32 }
33 var p2 = new Person("z3","男",18);
34 //p2.say();
35 var p3 = new Person("z4","女",20);
36 //p3.say();
37
38
39 //obj.constructor是obj的构造函数
40 alert(p2.constructor== Person ); //true
41
42 // 检验一个实例是不是 某实例的对象 instanceOf
43 alert(p2 instanceof Person); //true
44 alert(p2 instanceof Object); //true js中一切都是object的对象
45
46
47
48
49 // 3 不推荐使用的,绑定方法发利用call 或者apply
50 function Person(name , sex , age){
51 this.name = name;
52 this.sex = sex;
53 this.age = age;
54 this.say = function(){
55 alert(this.name +" "+this.sex+" "+this.age);
56 };
57 }
58 var o = new Object();
59 //利用call 可以绑定对象 给o绑定一个Person对象实例,内容是o之后的参数
60 Person.call(o,"z3","男",19);
61 o.say();
62