js中的繼承(es5)

weixin_33935777發表於2018-03-07

這個問題事關js裡面的很多難點的問題,諸如prototype,callapply等,也是js物件導向的問題,值得寫一篇.


  • call,apply
    callapply還是比較高階的用法,各個地方解釋不好懂,我的解釋就是:

改變某個方法執行時候的this指向,就是上下文環境,如果一個函式內輸出thisundefined,那麼,實際上,call是沒作用的,this存在在物件裡面

func.call(obj,param1,param2) //物件的引數分別寫
func.apply(obj,[param1,param2]) //物件的引數寫成array

例如:

var add_obj = {
    a:10,
    b:2
}
function sub_obj(a,b){
    console.log(this.a-this.b)
}
function add(a,b){
    console.log(a,b)
    console.log(this)
}
function sub(a,b){
    console.log(a-b)
}
 //1 僅僅執行sub,因為add中的this不存在,為undefined,不改變this指向
sub.call(add,2,1)
//1 相當於上面的輸出
sub.call(undefined,2,1) 
//8, add_obj有this指向,sub_obj執行時候,呼叫add_obj的上下文環境,所以用的是add_obj的this中的a,b
sub_obj.call(add_obj ,2,1) 
  • 繼承的實現
//父類animal
var animal = function(name,food){
    this.name = name
    this.food = food
    this.eat = function(){
        console.log("I like eating "+food)
    }
    this.action = function(){
        console.log("I can jump and run")
    }
}
//子類dog
var dog = function(name,food,praise){
    //實現:將animall的this指向dog的物件,dog的this就有了animal的方法
    //在class內執行,無需要例項化,變可以暴露給this
    animal.call(this,name,food)
    this.praise = function(){
        console.log(praise)
    }
}
//呼叫
var Dog = new dog("dog","bone","Most of us like dog")
Dog.eat()  //I like eating bone
Dog.action()  //I can jump and run
Dog.praise()  //Most of us like dog

  • prototype繼承
var animal = function(name,food){
    this.name = name
    this.food = food
    this.eat = function(){
        console.log("I like eating "+food)
    }
    this.action = function(){
        console.log("I can jump and run")
    }
}
var dog = function(praise){
    this.praise = function(){
        console.log(praise)
    }
}
//實現:其原型鏈指向animal的例項化物件
dog.prototype = new animal("dog","bone")

var Dog = new dog("Most of us like dog")
Dog.eat()  //I like eating bone
Dog.action()  //I can jump and run
Dog.praise()  //Most of us like dog

  • 建構函式繼承
var animal = function(name,food){
    this.name = name
    this.food = food
    this.eat = function(){
        console.log("I like eating "+food)
    }
    this.action = function(){
        console.log("I can jump and run")
    }
}
var dog = function(name,food,praise){
    //實現:講animal類給dog的this物件,然後屬性開啟,而非例項化
    this.temp = animal
    this.temp(name,food)
    this.praise = function(){
        console.log(praise)
    }
}

var Dog = new dog("dog","bone","Most of us like dog")
Dog.eat()
Dog.action()
Dog.praise()

  • 物件導向
    而且在用js開發時候,也可以用this或者prototype去進行物件化.

相關文章