1. json方法
1 var person = {
2 name: 'xm', 3 sex: 'male', 4 action: function () { 5 console.log(this.name); 6 } 7 }; 8 person.action(); 9 console.log(person);
输出如下
2. Object方法
1 var person = new Object();
2 person.name = 'xm'; 3 person.sex = 'male'; 4 person.action = function(){ 5 console.log(this.name); 6 }; 7 person.action(); 8 console.log(person);
3. 构造函数方法
1 function act(name, sex) {
2 this.name = name; 3 this.sex =sex; 4 this.action = function () { 5 console.log(this.name); 6 } 7 } 8 var person = new act('xm', 'male'); 9 person.action(); 10 console.log(person);
4. 工厂模式
1 function act(name, sex) {
2 var obj = new Object(); 3 obj.name = name; 4 obj.sex = sex; 5 obj.action = function () { 6 console.log(this.name); 7 }; 8 return obj; 9 } 10 var person = act('xm', 'male'); 11 person.action(); 12 console.log(person);
5.原型模式
1 function act() {
2 } 3 act.prototype.name = 'xm'; 4 act.prototype.sex = 'male'; 5 act.prototype.action = function () { 6 console.log(this.name); 7 }; 8 var person = new act(); 9 person.action(); 10 console.log(person);
6.混合模式 构造 + 原型
1 function act(name, sex) {
2 this.name = name; 3 this.sex = sex; 4 this.action = function () { 5 console.log(this.name); 6 }; 7 } 8 act.prototype = { 9 friend: 'xh', 10 say: function () { 11 console.log(this.friend); 12 } 13 }; 14 var person = new act('xm', 'male'); 15 person.action(); 16 person.say(); 17 console.log(person);