JavaScript
继承
原型链继承
function Parent() {
this.name = '父亲';
this.arr = [1];
}
Parent.prototype.say = function() {
console.log('hello')
}
function Child(like) {
this.like = like;
}
Child.prototype = new Parent()
let boy1 = new Child()
let boy2 = new Child()
console.log(boy1.say(), boy2.say(), boy1.say === boy2.say);
console.log(boy1.name, boy2.name, boy1.name===boy2.name);
boy1.arr.push(2);
console.log(boy2.arr);
注意:修改boy1的name属性,是不会影响到boy2.name。因为name是基本属性,不是引用属性。
构造函数继承
function Parent(name) {
this.name = name;
this.arr = [1];
this.say = function() {
console.log('hello')
}
}
function Child(name,like) {
Parent.call(this,name);
this.like = like;
}
let boy1 = new Child('小红','apple');
let boy2 = new Child('小明', 'orange ');
console.log(boy1.name, boy2.name);
boy1.arr.push(2);
console.log(boy1.arr,boy2.arr);
console.log(boy1.say === boy2.say)
的say方法是独立,不是共享的)
Parent.prototype.walk = function () {
console.log('我会走路')
}
boy1.walk;
组合继承
function Parent(name) {
this.name = name;
this.arr = [1];
}
Parent.prototype.say = function() {
console.log('hello')
}
function Child(name,like) {
Parent.call(this,name,like)
this.like = like;
}
Child.prototype = new Parent()
<!--这里是修复构造函数指向的代码-->
let boy1 = new Child('小红','apple')
let boy2 = new Child('小明','orange')
console.log(boy1.name,boy1.like);
console.log(boy1.say === boy2.say)
原型式继承
function object(o){
function F(){
}
F.pototype=o;
return new F()
}
let parent = {
name: 'parent',
share: [1, 2, 3],
log: function() {
return this.name
}
}
let child = Object.create(parent)
寄生继承
function createAnother(original){
var clone = object(original)
clone.sayHi = function(){
alert('hi');
}
return clone;
}
var person = {
name:"hello",
friends:['z',"x","p"]
}
var anotherPerson = createAnother(person);
anotherPerson.sayHi()
寄生组合继承
function Parent(name, friends) {
this.name = name
this.friends = friends
}
Parent.prototype = {
constructor: Parent,
share: [1, 2, 3],
log: function() {
return this.name
}
}
function Child(name, friends, gender) {
Parent.call(this, name, friends)
this.gender = gender
}
let F = function() {}
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child
function Parent(name, friends) {
this.name = name
this.friends = friends
}
Parent.prototype = {
constructor: Parent,
share: [1, 2, 3],
log: function() {
return this.name
}
}
function Child(name, friends, gender) {
Parent.call(this, name, friends)
this.gender = gender
}
function proto(child, parent) {
let clonePrototype = Object.create(parent.prototype)
child.prototype = clonePrototype
child.prototype.constructor = child
}
proto(Child, Parent)
ES2015 class extends
继承
lass Parent {
constructor(name, friends) {
this.name = name
this.friends = friends
}
log() {
return this
}
}
Parent.prototype.share = [1, 2, 3]
class Child extends Parent {
constructor(name, friends, gender) {
super(name, friends)
this.gender = gender
}
}