Julia's BLOG

js继承的四种方法

2019-03-17

1. 原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function Father(name) {
this.name = name;
}

Father.prototype.sayName = function() {
console.log("name is " + this.name);
}

var father = new Father("a");
father.sayName();

function Child(name) {
this.name = name;
}

Child.prototype = new Father();
var child = new Child("c");
child.sayName();

输出:

1
2
name is a
name is c

2. 通过 call() apply()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Father(name) {
this.name = name;
this.sayName = function() {
console.log("name is " + this.name);
}
}

function Child(name,age) {
// Father.call(this,name);
Father.apply(this,[name]);
this.age = age;
this.sayAge = function() {
console.log("age is " + this.age);
}
}

var child = new Child("c","21");
child.sayName();
child.sayAge();

输出:

1
2
name is c
age is 21

3. 原型链和 call() apply() 混合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* sayAge 两种方法都可以
*/
function Father(name) {
this.name = name;
}
Father.prototype.sayName = function() {
console.log("name is " + this.name);
}

function Child(name,age) {
Father.call(this,name);
this.age = age;
// this.sayAge = function() {
// console.log("age is " + this.age);
// }
}
Child.prototype = new Father();

Child.prototype.sayAge = function() {
console.log("age is " + this.age);
}

var child = new Child("c",21);
child.sayName();
child.sayAge();

输出:

1
2
name is c
age is 21

4. 对象冒充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Father(name) {
this.name = name;
this.sayName = function() {
console.log("name is " + this.name);
}
}

function Child(name) {
this.child = Father;
this.child(name);
delete this.child;
}

var child = new Child("c");
child.sayName();

输出:

1
name is c
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章