js繼承常用的三種方法屯援,記錄一下茎杂,馬上要面試了惫恼。
覺(jué)得有用可以幫我點(diǎn)個(gè)贊嗎鲸沮?謝謝了琳骡。
// 原型鏈繼承
function Parent() {
this.name = '原型鏈繼承';
this.play = [1,2,3];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() {
this.type = '原型鏈繼承child';
}
Child.prototype = new Parent();
// 原型鏈上的原型對(duì)象是通用的,改變一個(gè)讼溺,其他的都會(huì)改變楣号,但我們不想所有對(duì)象都改變
var child1 = new Child();
var child2 = new Child();
child1.play.push(4)
console.log(child1.play)
console.log(child2.play)
// 構(gòu)造函數(shù)繼承
function Parent() {
this.name = '構(gòu)造函數(shù)繼承';
this.play = [1,2,3];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() {
Parent.call(this)
this.type = '構(gòu)造函數(shù)繼承child';
}
var child1 = new Child();
console.log(child1.getName)
//構(gòu)造函數(shù)繼承不會(huì)繼承原型鏈上的方法
// 組合繼承
// 原理:創(chuàng)建中間對(duì)象,中間對(duì)象的原型對(duì)象是父類(lèi)的
function Parent() {
this.name = '組合繼承';
this.play = [1,2,3];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() {
Parent.call(this)
this.type = '組合繼承child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
//沒(méi)有這句代碼怒坯,Child.prototype.constructor會(huì)指向Parent
var child = new Child()
console.log(child instanceof Child,child instanceof Parent);
console.log(child.constructor);