重学第六章
1. 原型
- 实例内属性和原型上属性重名时(屏蔽)
function Test(name) {this.name = name
}
Test.prototype.name = 'hhh'
let tObj = new Test('yyy')
console.log(tObj.name) // yyy
tObj.name = null
console.log(tObj.name) // null
delete tObj.name
console.log(tObj.name) // hhh
- 实例的__proto__属性指向的对象有constructor属性,指向构造函数
function Test() {}
let tObj = new Test()
console.log('实例', tObj)
console.log('constructor', tObj.constructor)
console.log(tObj.constructor === tObj.__proto__.constructor)
- 实例(实例化的时候)的__proto__ 和构造函数的prototype全等,
function Test() {}
Test.prototype.name = 'name'
let tObj = new Test()
console.log('实例', tObj)
console.log('实例__proto__', tObj.__proto__)
console.log('prototype', Test.prototype)
console.log(tObj.__proto__ == Test.prototype)
-
切断了prototype 和 __proto__的联系,并且丢失了constructor
-
手动在字面量里添加constructor会让这个属性的[[Enumerabl]]变为true
-
可用Object.defineProperty(Car.prototype,constructor,{
enumerable:false,value:Car})
不加debugger
-
在实例化之后再改prototype (跟实例化前后也有点关系)
function Test() { }
Test.prototype.name = 'hhh'
Test.prototype = {name: '111'
}
let tObj = new Test()
Test.prototype.name = '666'
console.log(tObj.name) // 666
console.log(tObj.__proto__ === Test.prototype) // true
console.log(Test.prototype.isPrototypeOf(tObj)) // true
function Test() { }
Test.prototype.name = 'hhh'
Test.prototype = {name: '111'
}
let tObj = new Test()
Test.prototype = {name: '666'
}
console.log(tObj.name) // 111
console.log(tObj.__proto__ === Test.prototype) // false
console.log(Test.prototype.isPrototypeOf(tObj)) // false
2. 插件开发
- 放在IIFE里,能隔离作用域
; (function () {function Compute(a, b) {this.a = athis.b = b}Compute.prototype.plus = function () {return this.a + this.b}Compute.prototype.minus = function () {return this.a - this.b}Compute.prototype.multi = function () {return this.a * this.b}Compute.prototype.div = function () {return this.a / this.b}window.Compute = Compute
})()
let computeObj = new Compute(8, 2)
console.log('加', computeObj.plus()) // 10
console.log('减', computeObj.minus()) // 6
console.log('乘', computeObj.multi()) // 16
console.log('除', computeObj.div()) // 4