1. 程式人生 > >Javascript繼承(原始寫法,非es6 class)

Javascript繼承(原始寫法,非es6 class)

寫法 word key return .proto 設置 line 如果 space

知識點:

Object.create的內部原理:

Object.create = function (o) {

var F = function () {}; F.prototype = o; return new F(); }; 就是創建一個對象 然後把這個對象的__proto__原型對象指向o了 參數o是一個原型對象 下面講一下Javascript中的繼承: function Person(name){   this. name = name } // 在Person的原型對象上添加方法 Person.prototype.greet = function(){ console.log(` hello ${this.name}` } function Teacher(name){   Person.call(this,name) } /* 到此,Teacher和Person的原型對象上 都指向Object, constructor分別指向自身函數 // 將Teacher的原型對象設置 Teacher.prototype = Object.create(Person.prototype) /* 到此 Teacher的原型對象上沒有constructor屬性 如果調用實例化出來的teacher1的原型對象,就是在沿著原型鏈調用Person原型對象上的constructor Teacher.prototype.constuctor = Teacher 到此繼承完畢

Javascript繼承(原始寫法,非es6 class)