什么是面向对象? , 探讨一下面向对象中的几个概念:
1:一切事物皆对象
2:对象具有封装和继承特性
使用函数构造器构造对象:
//此处 构造器Person就是一个函数
function Person(name,age){
var obj=new Object();
obj.age=age;
obj.name=name;
obj.showage=function(){
alert(this.age);
}
obj.showname=function(){
alert(this.name);
}
return obj;
}
//使用new来构造一个对象
var P1=new Person(‘zh’,22);
P1.showname();
P1.showage();
面向对象中的原型:
//首字母大写构造函数不大写也可以称之为构造函数
function Person(name,age){
this.name=name;
this.age=age;
}
//prototype 原型
Person.prototype.showname=function(){
return this.name;
};
Person.prototype.showage=function(){
return this.age;
};
var p1=new Person(‘leo’,22);
var p2=new Person(‘zh’,22);
alert(p1.showname());
alert(p1.showage());
// alert(p1.showname()==alert(p2.showname());
alert(p2.showage()==p1.showage());
面向对象中的继承:
//要点:属性的继承用call或者apply 。方法的继承用for in (也就是拷贝继承)
//父类
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.showname=function(){
return this.name;
};
//子类
function Childperson(name,age,job){
//属性的继承
Person.call(this,name,age);
this.job=job;
}
//方法的继承—-利用exend解决了对象引用对父级产生的影响
exend(Childperson.prototype,Person.prototype)
Childperson.prototype.showjob=function(){
return this.job;
};
function exend(obj1,obj2){
for(var attr in obj2){
obj1[attr]=obj2[attr];
}
}
var p1=new Person(‘zenghuan’,22)
var p2=new Childperson(‘zh’,18,’程序员’)
// alert(p1.showname());
alert(p2.showname());
面向对象中的寄生组合继承:
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function(){
console.log(‘hello, my name is ’ + this.name);
};
function Man(name, age) {
Person.apply(this, arguments);
}
Man.prototype = Object.create(Person.prototype);//a.
Man.prototype.constructor = Man;//b.
var man1 = new Man(‘pursue’);
var man2 = new Man(‘joe’);
console.log(man1.say == man2.say);
console.log(man1.name == man2.name);