您的位置:首页 > Web前端 > JavaScript

JS的面向对象的基础

2015-07-16 22:27 771 查看
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js面向对象</title>
<script>
//父类
function Person(name,sex){
this.name=name;
this.sex=sex;
}
Person.prototype.showName = function(){
alert(this.name);
};
Person.prototype.showSex = function(){
alert(this.sex);
};
/****************继承********************/
//子类
function Other(name,sex,job){
Person.call(this,name,sex); //构造函数伪装
//OR Person.apply(this,arguments);
//OR person.apply(this,[name,sex]);
this.job=job;
}
for(var i in  Person.prototype){
Other.prototype[i] = Person.prototype[i]; //原型链
}
Other.prototype.showJob = function(){
alert(this.job);
}
/*****************继承***********************/
var oP = new Person('zimple','nan');
oP.showName();
oP.showSex();
var oW = new Other('zimple','nan','student');
oW.showName();
oW.showSex();
oW.showJob();
/*
在JS面向对象的过程中this的处理最为麻烦
在出现以下两种情况下,this的指向会发生变化
1)有绑定事件的时候
2)出现定时器的时候
解决方法:
可以将指向对象的this存为_this,然后在定时器或者绑定事件处再嵌套一个函数,使用_this代替
*/
</script>
</head>
<body>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面向对象 基础