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

js进阶学习之--面向对象继承

2016-08-05 23:42 531 查看
js进阶学习之--面向对象继承
JS中一共有三种继承方式:
1、prototype
2、call
3、apply

1.实现一个例子:
1) 创建三个对象 对象A  对象B  对象C 
2) A中有三个属性  a属性,b属性,c方法
3) B中有个2个属性  d方法,e方法
4) 使B继承A
5) C中有个1个属性   f属性
6) 使C继承B 并调用c方法

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>通过原型对象实现继承</title>
<script>

function A(){
this.a = "OK";
this.b = "YES";
}

A.prototype.c = function(){
console.log("我是C");
}

function B(){
this.ooo = "你好";
}

B.prototype = new A();

B.prototype.d = function(){
console.log("我是D");
}

B.prototype.e = function(){
console.log("我是E")
}

function C(){
this.name = "xcy";
}

C.prototype = new B();

var cObj = new C();

console.log(cObj);

</script>
</head>
<body>

</body>
</html>

call和apply实现继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>call和apply继承</title>
<script>

//原型继承方式弊端:无法向超类构造函数中传递参数
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}

Person.prototype = {
constructor:Person,
eat:function(){
console.log("吃饭");
},
say:function(){
console.log("说话");
}
}

function Programmer(){
this.charecter = "宅男";
this.aaa = "AAA";
}
Programmer.prototype = new Person();

Programmer.prototype.writeCode = function(){
console.log("写代码");
}

var programmer = new Programmer();

programmer.eat()

//call方法:
//call方法的第一个参数如果是对象的话会改写被调用函数中this指向,this的指向就会变成第一个参数这个对象
//fn01.call(obj);

//call或apply继承时的弊端:这两个方法继承时只能继承实例属性,无法继承原型对象下的属性

function Person(name,sex){
this.name = name;
this.sex = sex;
}
Person.prototype.eat = function(){
console.log("吃饭");
}
function Programmer(name,sex){
Person.call(this,name,sex);
}
var p = new Programmer("Tom","男");

function Person(){
this.name = arguments[0];
this.sex = arguments[1];
}

function Programmer(name,sex){
Person.apply(this,[name,sex]);
}

var p = new Programmer("张三","女");

console.log(p);

//var result = Math.max.apply(null,[2,1,3,-1]);//result=3
//var result = Math.min.apply(null,[2,1,3,-1]);//result=-1
//console.log(result);

</script>
</head>
<body>

</body>
</html>
组合继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组合继承</title>
<script>
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}

Person.prototype.eat = function(){
console.log("吃饭");
}

function Programmer(name,sex,age){
this.hobby = ["看书"];
Person.call(this,name,sex,age);
//使用call继承实例属性可以在实例化子类时向父类中传递参数
}

Programmer.prototype = Person.prototype;
//如果使用new Person(),会导致重复实例属性,并且Person构造函数会被调用两次

Programmer.prototype.writeCode = function(){
console.log("写代码");
}

var programmer = new Programmer("张三","男",30);
console.log(programmer);
</script>
</head>
<body>

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