Js原型鍊

  • 123
  • 0
  • Js
  • 2020-01-15

特性 : 最基本為物件,原型鍊為 物件 inherit 原型

定義原型

原型Constructer relation 原型

物件轉為原型使用 : Object.create(物件)、Object.create(函式.prototye)

多層Inheritance

__proto__ vs prototype

******************************************************************************************************

原型特性 : 具有物件的特性、向上查找、可共用方法及屬性

下方可以右邊看到 a物件的原型 : _proto_

可共用方法及屬性

            於a的物件,增加getname方法,圖中可以看到b的物件,有因原型中所加出的新方法

向上查找

            於a的原型,可看到為Array,在往下找可找到在上層為Object,所以在a 的Object上加入方法,可以在a的Array找到剛加入的方法

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

定義原型

1.定義原型函式
2.初始化物件
3.增加共同方法至原型函式~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

原型Constructer relation 原型

            a 為String、b為object (建構式)、String為原型函式,所以a與b透過原型String而建立出

            若需共同方法,則於String Prototype定義即可

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

物件轉為原型使用 : Object.create

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

多層Inheritance

console.log(ke.__proto__.constructor === Boy);
console.log(ke.__proto__ === Boy.prototype);
console.log(ke.__proto__.__proto__ === Person.prototype);
console.log(ke.__proto__.__proto__.constructor === Person);
console.log(Boy.__proto__ === Function.prototype);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

__proto__ vs prototype

            __proto__  物件上的屬性,非正式屬性, 正式屬性來源為向上源(物件、原型)

            prototype   函式上

 

ref : https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Inheritance_and_the_prototype_chain