属性继承的几种方式
1.原型继承:让子类的原型等于父类的实例,代码如下:
function Parent1() {
this.x = 100;
}
Parent1.prototype.getx = function getx() {
return this.x
}
function Child1() {
this.y = 200
}
Child1.prototype = new Parent1
var c1 = new Child1()
console.log(c1.x)
console.log(c1.y)
2.call继承:只能继承父类中私有的,不能继承父类中共有的,代码如下:
function Parent2() {
this.x = "100x"
}
Parent2.prototype.getx = function getx() {
return this.x
}
function Child2() {
Parent2.call(this)
this.y = "200y"
}
Child2.prototype.gety = function gety() {
return this.y
}
var c2 = new Child2()
console.log(c2.x)
console.log(c2.y)
3.es6中的类和继承,代码如下:
class Parent3 {
constructor() {
this.x = 100
}
getx() {
return this.x
}
}
class Child3 extends Parent3 {
constructor() {
super()
this.y = 200
}
gety() {
return this.y
}
}
var c3 = new Child3;
console.log(c3.x)
console.log(c3.y)