prototype
prototype的概念
几个概念:
1:一切引用数据类型都是对象。
2:对象是属性的集合。
3:对象都是通过构造函数创建的。
4:每个函数都有一个prototype属性,即原型。对象都有__proto__属性,可以成为隐式原型。这个__proto__属性是一个隐藏的属性,JS并不希望开发者能够用到这个属性,有的低版本浏览器甚至不支持这个属性值。
5:每个对象的__proto__属性指向创建该对象的函数的prototype。
6:Object.prototype.__proto__指向null。
访问一个对象的属性时,先在本地属性中查找,如果没有,再沿着__proto__这条链向上找,这就是原型链。
详解instanceof 运算符。 // 会沿着原型链查找。
详解hasOwnProperty方法。 // 不会沿着原型链查找。
详解isPrototypeOf方法。 // 会沿着原型链查找。
// var arr = new Array();
// console.log(arr.__proto__ === Array.prototype)
/* function Person(){
this.name = '张三';
this.age = 26;
}
Person.prototype.say = function(){}*/
// instanceof 判断对象(Person)是不是构造函数(oPerson)的实例,沿原型链找
var oPerson = new Person();
console.log(oPerson instanceof Object) //true
console.log(oPerson instanceof Person) //true
// xx.hasOwnProperty('属性') 判断自身是否拥有某个属性,不是沿原型链找
console.log(oPerson.hasOwnProperty('age')) //true
console.log(oPerson.hasOwnProperty('say')) //false
// isPrototypeOf() 沿原型链找,判断prototype对象和某个实例之间的关系
console.log(Person.prototype.isPrototypeOf(oPerson)); //true
// in 沿原型链找,用来判断,某个实例是否含有某个属性,不管是不是本地属性。
console.log('say' in oPerson)
//------------------------原型链继承-----------------------------------------
function Person(){
this.hobby = '运动';
}
function Man(){
}
// 原型继承
Man.prototype = new Person();
Man.prototype.constructor = Man; // 必须将构造函数更正过来
var oMan = new Man();
//-----------------------------混合继承--------------------------------------
function Person(sex){
this.name = '翠花';
this.hobby = '运动';
this.sex = sex;
}
Person.prototype.eat = function(){
console.log('白痴')
function Wuman(){
// call和apply继承属性
Person.call(this,'女')
}
Wuman.prototype.flower = function(){
console.log('玫瑰');
}
// 原型链用于继承方法
Wuman.prototype = new Person();
var oWuman = new Wuman();
console.log(oWuman);
// oWuman.flower();
oWuman.eat();