原型和原型链
原型及原型链模式
每个函数数据类型的值都有一个天生自带的属性:prototype,这个属性的属性值是一个对象(用来存储实例公用的属性和方法)
- 普通函数
- 类(自定义类和内置类)
在prototype这个对象中,有一个天生自带的属性:constructor,这个属性存储的是当前函数本身
Fn.prototype.constructor === Fn每个对象数据类型的值,也有一个天身自带的属性:__ proto__ 属性,这个属性指向'所属类的原型prototype'
- 普通对象、数组、正则、Math、日期、类数组等
- 函数的原型prototype属性也是对象类型的
- 函数也是对象数据类型的值
原型链查找机制
- 先找自己私有的属性,有则调取使用,没有继续找
- 基于_proto_ 找到所属类原型上的方法(Fn.prototype),如果还没有则继续基于_proto_ 往上找... 一直找到Object.prototype为止
hasOwnProperty
检测某个属性名是否为当前对象的私有属性
'in' : 检测这个属性是否属于某个对象(不管私有属性还是公有属性,只有是它的属性,结果就为true)
lat ary = [10,20,30];
console.log('0' in ary); //=> ture
console.llog('push' in ary); //=> ture
console.log(ary.hasOwnProperty('0')) //=>true
console.log(ary.hasOwnProperty('push')) //=> false
console.log(Array.prototype.hasOwnProperty('push')) //=> true 是共有还是私有属性,需要看相对谁来说的
console.log(Array.prototype.hasOwnProperty('hasOwnProperty')) //=>false
// IE中__proto__被保护起来了,不让使用
扩展
检测某个属性是否为对象的共有属性: hasPubProperty
方法:是它的属性,但是不是私有的
//基于原型扩展方法
Object.prototype.hasPubProperty = function(property){
//验证属性的合法性
if(!["string","number","boolean"].includes(typeof property)) return false
//开始校验是否为公有属性
let n = property in this,
m = this.hasOwnProperty(property);
return n&&!m
}
console.log(Array.prototype.hasPubProperty('push')); //=>false
console.log([].hasPubProperty('push')) //=> ture;

浙公网安备 33010602011771号