1.任何函数都有prototype属性,prototype是英语‘原型’的意思,prototype属性值是个对象,它默认拥有constructor属性指回函数
function sum(a,b){
return a+b;
}
console.log(sum.prototype) // {constructor;f}
console.log(typeof sum.prototype) //object
console.log(sum.prototype.constructor===sum) //true
2.构造函数的prototype是实例的原型
function People(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
var xiaoming=new People('小明',25,'男')
console.log(xiaoming.__proto__ === People.prototype) //true
3.实例可以打点访问它的原型的属性和方法,这被称为‘原型链查找’
function People(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
People.prototype.height='178'
var xiaoming=new People('小明',25,'男')
console.log(xiaoming.height) //178
4.hasOwnProperty方法可以检查对象是否真正‘自己拥有某属性或者方法’
console.log(xiaoming.hasOwnProperty('name')) //true
console.log(xiaoming.hasOwnProperty('age')) //true
console.log(xiaoming.hasOwnProperty('sex')) //true
console.log(xiaoming.hasOwnProperty('height')) //false
5.in运算符只能检查某个属性或方法是否可以被对象访问,不能检查是否是自己的属性或方法
console.log('name' in xiaoming) //true
console.log('age' in xiaoming) //true
console.log('sex' in xiaoming) //true
console.log('height' in xiaoming) //true
6.方法要写到prototype上,因为如果加到实例上每个实例和每个实例的方法函数都是内存中不同的函数,造成了内存的浪费
function People(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
People.prototype.sayHello=function(){
console.log('大家好,我是'+this.name)
}
People.prototype.sleep=function(){
console.log(this.name+'开始睡觉,zzzz~~')
}
var xiaoming=new People('小明',25,'男')
var xiaohong=new People('小红',18,'女')
console.log(xiaoming.sayHello === xiaohong.sayHello)
7.原型链的终点 Object.prototype
function People(){
}
var xiaoming=new People()
console.log(xiaoming.__proto__.__proto__ === Object.prototype) //true
console.log(Object.prototype.__proto__) //null
8.数组的原型链
var arr=[12,13,16,9]
console.log(arr.__proto__ === Array.prototype) //true
console.log(arr.__proto__.__proto__ === Object.prototype) //true
console.log(Array.prototype.hasOwnProperty('push')) //true
console.log(Array.prototype.hasOwnProperty('splice')) //true