javascript面向对象

什么是面向对象? , 探讨一下面向对象中的几个概念:
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);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值