原型
- 誰調用,this就指向誰,當實例對象有該屬性時,不會去原型上查找
- 創建對象的兩種方法:字面量、new Object()一般不用后面的
- 二者創建出來的對象沒有差異
Object.create()
- var 實例 = Object.create(對象/null)
- 將對象或null作為實例的原型
- new構造函數的時候做了什么
- 實例化對象
- 調用構造函數的初始化屬性和方法
- 指定實例對象的原型
- 將null作為實例的原型,原型中將不包含任何屬性!
- 因此,不是所有對象都繼承Object.prototype
- 無法查找到toString方法(沒有__proto__)
- 手動增加的__proto__和自身的不一樣,沒有可以向上查找的原型鏈
var obj = Object.create(null)
obj.num = 1;
var obj1 = {count: 2
}
obj.__proto__ = obj1;
console.log(obj.count) // undefined
obj.toString() // 報錯
-
document.write接收字符串,當傳入非String類型時,會先調用相應的toString方法
-
原始值是沒有屬性的,基本包裝類有屬性和方法(有toString)
-
除了undefined、null,其他的基本數據類型(Number、String、Boolean)都有自己的toSting方法
-
基本數據類型的toSting方法和Object.prototype的toSting方法不同
原型鏈
- 原型鏈的終點是Object.prototype
對象繼承
- 將父級的實例作為我的原型對象
function GrandFather() {this.name = '祖先'
}
var grandFatherObj = new GrandFather() // 將父級的實例作為我的原型對象function Father() {this.name = '父親'
}
Father.prototype = grandFatherObj
var fatherObj = new Father()
function Child() {this.name = '孩子'
}
Child.prototype = fatherObj
var childObj = new Child()
console.log('祖先實例', grandFatherObj)
console.log('父親實例', fatherObj)
console.log('孩子實例', childObj)
- 祖先的實例中的__proto__指向祖先的原型對象,構造器指向構造函數GrandFather
- 祖先原型對象里也有__proto__指向Object.prototype,構造器指Object構造函數
- Object.prototype有toString方法
- 孩子實例修改父親的引用數據類型的屬性
- 孩子實例不能修改父親的基本數據類型的屬性
- 對于++操作符 相當于student.students = 1 + student.students(先讀取再賦值),會在孩子實例上創建這個屬性
調用方法時改變函數內this指向
call\apply\bind
方法.call(this指向的對象,參數…)
方法.apply(this指向的對象,arguments)
- 插件計算器 方法寫在prototype里更合適
; (function () {function Compute() {this.plus = function (a, b) {return a + b}this.minus = function (a, b) {return a - b}}function FullCompute() {Compute.call(this)this.multi = function (a, b) {return a * b}this.divide = function (a, b) {return a / b}}window.FullCompute = FullCompute
})()
var myFullCompute = new FullCompute()
console.log('加', myFullCompute.plus(8, 2)) // 10
console.log('減', myFullCompute.minus(8, 2)) // 6
console.log('乘', myFullCompute.multi(8, 2)) // 16
console.log('除', myFullCompute.divide(8, 2)) // 4
function Car(brand, color) {this.brand = brandthis.color = color
}
function Person(name, age) {this.name = namethis.age = agethis.printFn = function () {Car.call(this, 'Bentley', '黑')console.log(this.name + this.age + '歲的生日禮物是一輛' + this.color + '色的' + this.brand)}
}
var me = new Person('Stephy', 20)
me.printFn()
console.log('me', me)