JavaScript - 理解原型

來源:互聯網
上載者:User

標籤:logs   variable   屬性   symbol   它的   tin   null   prot   訪問速度   

Function對象特有的屬性 prototype

所有對象都有的屬性 __proto__

 

1、用法

const F = function (name) {  this.name = name  }F.prototype.greeting = function () {  console.log(‘hello‘, this.name)}let f1 = new F(‘osyo‘)let f2 = new F(‘mioco‘)f1.greeting() // hello osyof2.greeting() // hello mioco

可以看出,prototype主要用來放共有的屬性和方法,這樣你就不用每次new的時候都執行個體化那個屬性了。

 

2、prototype和__proto__的關係

方法對象都有這兩個屬性,prototype是該方法的原型,__proto__是它父親的原型(Object作為生命的起源它的__proto__為null)

 

3、應用舉例

1) underscore.js代碼節選

  // Save bytes in the minified (but not gzipped) version:  var ArrayProto = Array.prototype, ObjProto = Object.prototype;  var SymbolProto = typeof Symbol !== ‘undefined‘ ? Symbol.prototype : null;  // Create quick reference variables for speed access to core prototypes.  var push = ArrayProto.push,      slice = ArrayProto.slice,      toString = ObjProto.toString,      hasOwnProperty = ObjProto.hasOwnProperty;

 underscore在這裡把原生對象的原型儲存在變數中以加快訪問速度,因為原型鏈的索引是當前對象->對象原型->父親的原型->...->Object原型,順著鏈子往上找還是挺耗時的大約...(話說這個例子感覺用來舉例原型鏈比較合適的樣子...)

 

2) classes polyfill

我們知道ES6中新增了一個文法糖Class

ES6:

class F {  constructor (name) {    this.name = name  }  greet () {    console.log(‘hello ‘ + this.name)  }}class SubF extends F{  constructor () {    super(‘osyo from subF‘)  }  subGreet () {    super.greet()  }}let f = new SubF()f.subGreet() //hello osyo from subF

等價於ES5:

function F (name) {  this.name = name}F5.prototype.greet = function () {  console.log(‘hello ‘ + this.name)}F5.greetAll = function () {  console.log(‘hello everybody‘)}function SubF () {  F.call(this, ‘osyo from subF‘)}
// 繼承屬性SubF.prototype = Object.create(F.prototype)SubF.prototype.contructor = FSubF.greetAll = F.greetAll

//子類方法的屬性SubF.prototype.subGreet = function () { F5.prototype.greet.call(this)}
let f = new SubF5()f.subGreet() //hello osyo from subF

 

JavaScript - 理解原型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.