js实现继承的方式,有原型链,call,apply,es6的class,个人感觉这几个用的最多,随着es6以及后续版本的不断发展,这种偏向后台的语法糖写法博主最为喜欢,博主也是做java出身的哈。
<!DOCTYPE html>
<html>
<head>
<meta chart="utf-8" />
<title>js实现继承常用的几种方式</title>
</head>
<body>
<script>
// 定一个Animal的基类,子类会继承say()方法输出自己的信息
function Animal(name) {
this.name = name || "Animal";
this.say = function() {
console.log("i'm ", this.name, " 来自对象:", this)
}
}
// 原型链实现继承
function Cat1() {}
Cat1.prototype = new Animal();
Cat1.prototype.name = "Cat1";
// 运行
var cat1 = new Cat1();
cat1.say();
// 使用call来实现继承
function Cat2(name) {
Animal.call(this, name);
}
// 运行
var cat2 = new Cat2("Cat2");
cat2.say();
// 使用apply来实现继承
function Cat3(name) {
Animal.apply(this, [name]);
}
// 运行
var cat3 = new Cat3("Cat3");
cat3.say();
// 使用es6的语法class来实现继承,需要包含构造函数
class Cat4 extends Animal {
constructor(props) {
super(props);
}
}
// 运行
var cat4 = new Cat4("Cat4");
cat4.say();
</script>
</body>
</html>
下面是运行效果: