面向对象是一项非常有用的模式,js在初生时并没有考虑太多这方面的问题,后来无数js大牛创造出了这种模式,感觉js创建对象的方法也有很多,工厂模式,原型模式,构造函数模式等等。。。。各大教科书高程什么的讲得很全,个人筛选出了可能比较好的两种模式,毕竟没法记住所有的方法。。
创建对象
法一:组合使用构造函数模式和原型模式
function Person(name,sex,height){
this.name = name;
this.sex = sex;
this.height = height;
this.friend = ["liao","liaoliao"];
}
Person.prototype = {
construtor :Person,
say : function(){
console.log("i'm "+this.name);
}
}
个人的想法是,构造函数中定义好这个对象所含有的变量,而原型方面定义好这个对象的函数,从而实现了“属性”和“功能”的分离,创建多个对象时也不会影响这里的friends数组,不是引用而是创建
法二:稳妥构造函数(不是寄生式构造,寄生式构造不能用instanceof确定对象类型,不建议使用寄生式构造)
function Person(name,sex,height){
var o=new Object();
var name = name;
var sex = sex;
var height = height;
var friend = ["liao","liaoliao"];
o.say = function(){
console.log("i'm "+name);
}
return o;
}
var person1 = new Person("liao","boy",150);
person1.say();
console.log(person1.friend);
person1.name="gg";
person1.say();
这种构造方式最大的特点就是安全,封装性很好,不可以改变定义好对象的内部变量,但要注意三点(在某博客上看到的)
注意: (以下3点)
1. 在稳妥构造函数中变量不能挂到要返回的对象o中
2. 在稳妥构造函数中的自定义函数操作元素时使用不要用this
3. 在函数外部使用稳妥构造函数时不用new。
较为完整的测试代码(带了个继承)
function Person(name,sex,height){
this.name = name;
this.sex = sex;
this.height = height;
this.friend = ["liao","liaoliao"];
}
Person.prototype = {
construtor :Person,
say : function(){
console.log("i'm "+this.name);
}
}
//寄生式构造
// function Person(name,sex,height){
// var o = new Object();
// o.name = name;
// o.sex = sex;
// o.height = height;
// o.friend = ["liao","liaoliao"];
// o.say = function(){
// console.log("i'm "+this.name);
// }
// return o;
// }
//稳妥构造
// function Person(name,sex,height){
// var o=new Object();
// var name = name;
// var sex = sex;
// var height = height;
// var friend = ["liao","liaoliao"];
// o.say = function(){
// console.log("i'm "+name);
// }
// return o;
// }
// var person1 = Person("liao","boy",150);
// person1.say();
// console.log(person1.friend);
// person1.name="gg";
// person1.say();
function Superman(){
var superman = new Person();
superman.name = "wyp";
superman.fly = function(){
superman.say.call(this);
console.log(this.name+" is flying");
};
return superman;
}
var person1=new Person("yao","公",150);
var person2=new Person("ji","母",160);
person1.say();
console.log(person1.friend);
person1.friend.push("bulaili");
console.log(person1.friend);
console.log(person2.friend);
person2.say();
person1.name="2333";
person1.say();
var wyp=new Superman();
wyp.fly();
wyp.name = "daer";
wyp.fly();
上述用的是寄生式继承,个人觉得传统的原型链+组合函数-》组合继承,比较散化封装性不太好,写多了容易逻辑混乱
然后看了看寄生式继承与寄生式组合继承,两者非常像:思路都是创建对象->增强对象->返回对象,于是没有就着高程上所写的把构造函数借用和原型链操作分开,而是做了个封装觉得这样的风格最好吧~,虽然只是个寄生式继承orz