Grand.prototype.lastname ='J'functionGrand(){this.name ='Mike'}var grand =newGrand();Father.prototype = grand;functionFather(){this.name ='Bob'}var father =newFather();Son.prototype = father;functionSon(){this.name ='Tom'}var son =newSon();
Father.prototype.lastname ='J';functionFather(){}functionSon(){}// Son.prototype = Father.prototypefunctioninherit(Target,Origin){Target.prototype =Origin.prototype;}//将Son.prototype = Father.prototype这句的功能变为函数inherit(Son,Father);//调用inherit函数var son =newSon();var father =newFather();Son.prototype.age =19;//当进行此句时,Father的prototype.age也会变为19。//因为两个函数的prototype都指向同一空间。//所以一个发生改变,另一个也会发生改变
圣杯模式
写法1
functioninherit(Target,Origin){functionF(){};F.prototype =Origin.prototype;Target.prototype =newF();//顺序很重要Target.prototype.constructor = Target;Target.prototype.uber =Origin.prototype;}Father.prototype.lastname ='J';functionSon(){this.name ='Mike';}functionFather(){this.name ='Tom';}inherit(Son,Father);Son.prototype.age =19;var son =newSon();var father =newFather();//此时son.age = 19//father.age为undefined//实现共同继承,也可以拥有自己的prototype属性
写法2
var inherit =(function(){varF=function(){};//此时F为该函数内部的私有变量returnfunction(Target,Origin){F.prototype =Origin.prototype;Target.prototype =newF();Target.prototype.constructor = Target;Target.prototype.uber =Origin.prototype;}//将该函数体返回}())//立即执行函数inherit(Son,Father);Father.prototype.lastname ='J';functionSon(){this.name ='Mike';}functionFather(){this.name ='Tom';}Son.prototype.age =19;var son =newSon();var father =newFather();
两种方法实现功能一致
模仿jQuery库实现连续调用
var person ={name:function(){
console.log('name');returnthis;},age:function(){
console.log(19);returnthis;},sex:function(){
console.log('male');returnthis;}}
person.name().age().sex()// 结果:// name// 19// male
属性的表示方法
var score ={NO1:'90',NO2:'89',NO3:'85',NO4:'80',search:function(num){returnthis['NO'+ num];//实现字符串拼接//若不用字符串拼接,则必须用switch结构或是if结构来实现功能}}//score.NO1相当于score[NO1]//系统内部实现score.NO1 -->score[NO1]
对象枚举
for in
var person ={
name :'Mike',
age :19,
sex :'male'};for(var prop in person){
console.log(person[prop]);}//结果: //Mike//19//male
hasOwnProperty方法
var person ={
name :'Mike',
age :19,
sex :'male',
__proto__ :{
height :180,}};for(var prop in person){if(person.hasOwnProperty(prop)){
console.log(person[prop]);}}//当没有if判断时,会打印Mike,19,male,180//加上if判断后,hasOwnPrototype方法判断当前属性是否为系统自设,若不是系统自设属性,则打印,反之,则不进行操作//结果://Mike//19//male
in
var person ={
name :'Mike',
age :19,
sex :'male',
__proto__ :{
height :180,}};// 'name' in person// 返回true// 'height' in person// 返回true
instanceof
A instanceof B
A对象是不是B构造函数沟造出来的
看A的原型链上的有没有B的原型
functionPerson(){};var person =newPerson();var obj ={};// person onstanceof Person// 结果:true// [] instanceof Array// 结果:true// obj instanceof Object// 结果:true