1.传统js对象生成方式
①var nam = {name = "hkj"
age = "20"
}
②var man1 = {};
man1.name = "hkj";
man1.age = 20;
2.方法改进
function Man(name,age) {return {
name:name;
age:age
}
}
var man2 = Man("hkj",20);
3.构造函数
function Man(name,age) {this.name = name;
this.age = age;
this.work = function(){alert("人都需要工作");}
}
var man3 = new Man3("hkj",20);
vat man4 = new Man4("h",21);
alert(man3.age);
alert(man4.name);
由构造函数生成的对象都具有同一个constructor属性,指向构造函数
man3.construcor == man4.constructor == Man
可用instanceof运算符判断对象与类的关系
alert(man3 instanceof Man);//true
缺点:每个不同对象都存在一个相同的work方法,但每次生成对象时work都会生成一次,占用内存
4.prototype(原型)模式
prototype为构造函数的一个属性,指向另一个对象,该对象所有属性方法都会被构造函数实例继承。一般用来存放公有方法和属性。function Man(name,age){
this.name = name;
this.age = age;
}
Man.prototype.work = function(){alert("人都需要工作");{}
var man5 = new Man("hkj",20);
man5.work();
优点:所有实例对象的work方法都使用了同一个内存地址指向了prototype对象,提高了效率。
相关方法:
alert(Man.prototype.isPrototypeOf(man5)); //true 判断prototype与实例之间的关系
alert(Man.hasOwnProperty("name")); //true 判断是否是本地属性
alert("name" in man5); //true 判断是否含有某个属性
5.继承
①构造函数继承
function People(){this.type="人";
}
function Man(name){
this.name=name;
People.apply(this,arguments); //将子类构造函数与父类构造函数绑定
People.call(this,name); //与apply方法功能相同,区别后面需要传入所有参数,而apply传入参数数组
}
var man=new Man("hkj");
alert(man.type);
②prototype继承
function Person(){this.type="人";
}
function Man(name){
this.name=name;
}
Man.prototype=new Person(); //将man的prototype指向Person实例
Man.prototype.constructor=Man; //手动纠正由上一行导致man的构造函数为Person的错误
var man=new Man("hkj");
alert(man.type);
③prototype直接继承
function Person(){}Person.prototype.type="人";
function Man(){}
Man.prototype = Person.Prototype;
Man.prototype.constructor=Man;
var man=new Man();
alert(man.type);
缺点:Man和Person的prototype变成了同一个,任何对子类的修改将影响到父类。而且后面的手动纠正也将Person的构造函数变成了Man的构造函数
④空对象继承 //对于直接继承的一种改进,利用中介对象消除手动纠正对父级构造函数的影响
function Person(){}Person.prototype.type="人";
function Man(){}
function F(){}
F.prototype=Perosn.prototype;
Man.prototype=new F();
Man.prototype.constructor=Man();
方法封装:
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype; //连接Child与Parent,备用性质
}
⑤拷贝继承
function extend2(Child, Parent) {var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}