標籤: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 - 理解原型