注意:博文中提到的「屬性」,指的是「屬性+方法」,這裏統稱爲「屬性」;html
var obj = new Object(); 使用構造函數new一個對象實例(因此程序員每天都在談對象,哈哈哈)程序員
特色:app
function Animal() { this.type = '動物'; } Animal.prototype.getType = function(){ console.log(this.type); } let animal = new Animal(); console.log(animal.type); // 動物 animal.getType(); // 動物
Child.prototype = new Parent(); 將父類的實例做爲子類的原型ssh
特色:函數
function Animal() { this.type = '動物'; } Animal.prototype.getType = function(){ console.log(this.type); } function Cat(){ this.vary = '貓'; } Cat.prototype.getVary = function(){ console.log(this.vary); } Cat.prototype = new Animal(); var cat = new Cat(); // cat.getVary() // 報錯:cat.getVary is not a function [緣由:Cat.prototype = new Animal()的操做覆蓋了原型鏈] console.log(cat.constructor); // Animal 這個constructor實質調用的是Animal.prototype.constructor // 修改Cat類的constructor爲Cat Cat.prototype.constructor = Cat; console.log(cat.constructor); // Cat cat.getType(); // 動物 // 修改Cat類prototype上的getType方法,看是否影響Animal類的getType方法 Cat.prototype.getType = function(){ console.log('我是貓科類'); } var animal = new Animal(); animal.getType(); // 動物
在子類的構造體中,使用call、apply、bind方法,讓父類方法中的this指向子類的實例,也就是改變this的上下文環境。學習
特色:this
Function.prototype.call2 = function () { var ary = [...arguments].slice(1); if (!arguments[0]) { this(...ary); } else { var obj = Object(arguments[0]); // 將參數變成一個對象 obj.__proto__.fn = this; obj.fn(...ary); delete obj.__proto__.fn; } };
function Animal() { this.type = '動物'; } Animal.prototype.getType = function(){ console.log(this.type); } function Cat(){ Animal.call(this); this.vary = '貓'; } Cat.prototype.getVary = function(){ console.log(this.vary); } var cat = new Cat(); console.log(cat.type); // 動物 // cat.getType(); // Uncaught TypeError: cat.getType is not a function cat.type = '貓科動物'; var animal = new Animal(); console.log(animal.type); // 動物
var child = Object.create(obj, props); spa
我先來一段Object.create的實現方式(看懂原理很重要)prototype
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
咱們這裏只分析參數obj的騷操做,能夠看出來,Object.create是內部定義一個對象,而且讓F.prototype對象賦值爲引進的對象/函數 o,並return出一個對象的實例。code
只要看懂了原理,咱們能夠參考「原型鏈繼承」的方式去理解這種繼承方法;
function Animal() { this.type = '動物'; } Animal.prototype.getType = function(){ console.log(this.type); } var cat = Object.create(new Animal(), { vary: { value: '貓科動物' } }); console.log(cat.constructor); // Animal 這個constructor實質調用的是Animal.prototype.constructor console.log(cat.type); // 動物 cat.getType(); // 動物 console.log(cat.vary); // '貓科動物'