封装类
1. 工厂模式
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function createPerson(name, age){ var obj = new Object(); obj.name = name; obj.age = age; obj.sayName = function(){ console.log(this.name); // | console.log(obj.name) }; return obj; } var p1 = createPerson("ys", 12); var p2 = createPerson("ys", 12); console.log(p1); // { name: 'ys', age: 12, sayName: [Function] } console.log(p2); // { name: 'ys', age: 12, sayName: [Function] } console.log(p1 == p2); //false |
特点:
- 内部创建对象,外部返回,相当于调用函数,
- 对象无类型(比如其他oo语言,new一个对象,那个这个对象的构造函数就是对象类型)
2.构造函数模式
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function Person(name, age){ this.name = name; this.age = age; this.sayName = function(){ console.log(this.name); }; } var p1 = new Person("ys", 12); var p2 = new Person("ys", 12); console.log(p1); // { name: 'ys', age: 12, sayName: [Function] } console.log(p2); // { name: 'ys', age: 12, sayName: [Function] } console.log(p1 == p2); //false console.log(p1 instanceof Person); //true console.log(p2 instanceof Person); //true console.log(p1 instanceof Object); //true console.log(p2 instanceof Object); //true console.log(p1.constructor == Person); //true /*constructor属性为构造函数属性,指向构造函数Person*/ console.log(p2.constructor == Person); //true |
特点: Continue reading