在面向開發對象開發過程中對每一個實例添加方法,會使每一個對象都存在該添加方法造成空間浪費
通過對原型添加公共的屬性或方法,使所有實例對象都可訪問
原型為了共享公共的成員 ?prototype
原型: JS為每個構造函數提供一個屬性prototype(原型),它的值是一個對象,prototype也叫原型對象
constructor屬性,原型對象的默認屬性->原型對象的構造函數
function Cat(name, age) {this.name = namethis.age = age
}Cat.prototype.eat = function () {console.log('貓吃老鼠')}
Cat.prototype.nation = 'china'const cat1 = new Cat('加菲貓', 3) // {name: '',age: ,eat}const cat2 = new Cat('銀漸層', 4) // {name: '',age: ,eat() {}}console.log(cat1.age)console.log(cat1.nation)cat1.eat()cat2.eat()console.log(cat1.eat === cat2.eat) // true
console.log(Cat.prototype)console.log(Cat.prototype.constructor === Cat) // true
console.log(Array.prototype.constructor === Array) // trueconst arr = [] // new Object()console.log(arr.constructor === Array) // trueconsole.log(arr.constructor === Array.prototype.constructor) // trueconsole.log(arr.constructor) // 訪問arr數組對象的constructor,會到原型去訪問console.log(Object.prototype.constructor) // Object ;const obj = {}console.log(obj.constructor) // Objectconst obj2 = { a: 1 }console.log(obj.constructor === obj2.constructor) // true
?訪問對象成員的原則: 先查找自己身上有沒有,有的話就使用,沒有去原型查找
?prototype->原型對象 __proto__ 原型
constructor屬性,原型對象的默認屬性->原型對象的構造函數
每個對象都有一個__proto__屬性,指向原型對象
function Person(name, age) {this.name = namethis.age = age}Person.prototype.say = function () {console.log('saying')}const p1 = new Person('小明', 20)console.log(p1.name)p1.say()console.log(p1.__proto__)console.log(p1.constructor.prototype.constructor)console.log([].__proto__) // Array.prototype {constructor: Array,...}console.log([].__proto__.constructor) // Arrayconsole.log([].constructor) // Arrayconsole.log('123'.constructor) // Stringconsole.log(Array.prototype) const arr = [1,2,3]arr.push(4)
數組拓展方法
Array.prototype.getSum = function () {console.log(this) // this 指向getSum調用著->實例對象let sum = 0this.forEach(function (item) {sum += item})return sum}const arr = [1, 2, 3]const arr2 = [10, 3, 4]arr2.getSum()const res = arr2.getSum()console.log(res)
對象訪問成員的機制
?1 ?首先查找自身有沒有,有就就近原則使用
?2 ?自身沒有該成員,通過__proto__找到原型對象,看原型對象上有沒有,有就執行
? 3 ?假如原型對象上也沒有,再找原型對象的__proto__ ,一直找到Object.prototype
?4 ?一直找到Object.prototype,找不到就undefined
每一個實例對象又有一個proto屬性,指向的構造函數的原型對象,構造函數的原型對象也是一個對象,也有proto屬性,這樣一層一層往上找就形成了原型鏈
Date.now() 靜態方法
Array.isArray
Array.from
?str.substring()
?Object.assign