一、继承发展史
a:传统形式->原型链
过多了继承了不要的属性
1 Father.prototype.lastName = ‘Fan‘; 2 3 function Father(){ 4 5 } 6 7 Son.prototype = father; 8 9 function Son(){ 10 11 } 12 13 var son = new Son() 14 console.log(son)
b:借用构造函数(call,apply)
1 function Person(age,height,weight){ 2 this.age = age; 3 this.height = height; 4 this.weight = weight; 5 } 6 7 function Student(age,height,weight,grade){ 8 Person.call(this,age,height,weight); 9 this.grade = grade; 10 } 11 12 var student = new Student(18,160,90,‘100分‘) 13 console.log(student)
不能继承借用构造函数的原型
每次构造函数都要夺走一个函数
c:共享函数
1 Father.prototype.lastName = ‘Fan‘; 2 function Father(){ 3 4 } 5 6 Son.prototype = Father.prototype 7 8 var son = new Son();//son.lastName Fan 9 var father = new Father();//father.lastName Fan
1 Father.prototype.lastName = ‘Fan‘; 2 function Father(){ 3 } 4 function Son(){ 5 } 6 function inherit(Target,Origin){ 7 Target.prototype = Origin.prototype 8 } 9 inherit(Son,Father); 10 var son = new Son(); 11 console.log(son)
不能随便改动自己的原型(Son的原型改了,Father的原型也会被改)
d:圣杯模式(既共有了属性,随便修改也不会改变另一个构造函数的原型)
1 Father.prototype.lastName = ‘Fan‘; 2 function Father(){ 3 } 4 function Son(){ 5 } 6 7 function inherit(Target,Origin){ 8 function F(){}; 9 F.prototype = Origin.prototype; 10 Target.prototype = new F(); 11 } 12 13 inherit(Son,Father); 14 var father = new Father(); 15 var son = new Son(); 16 17 console.log(son,father)
(圣杯模式)继承方法
1 Father.prototype.lastName = ‘Fan‘; 2 function Father(){ 3 } 4 function Son(){ 5 } 6 7 function inherit(Target,Origin){ 8 function F(){}; 9 F.prototype = Origin.prototype 10 Target.prototype = new F(); 11 Target.prototype.constructor = Target; 12 Target.prototype.uber = Origin.prototype; 13 } 14 15 inherit(Son,Father); 16 var father = new Father(); 17 var son = new Son(); 18 console.log(son,father)
最完美的圣杯模式(继承方法)
1 Father.prototype.lastName = ‘Fan‘; 2 function Father(){ 3 } 4 function Son(){ 5 } 6 var inherit = (function(){ 7 var F = function (){}; 8 return function(Target,Origin){ 9 F.prototype = Origin.prototype 10 Target.prototype = new F(); 11 Target.prototype.constructor = Target; 12 Target.prototype.uber = Origin.prototype; 13 } 14 }()) 15 inherit(Son,Father); 16 var father = new Father(); 17 var son = new Son(); 18 console.log(son,father)
二、命名空间
管理变量,防止污染全局,适用于模块开发。
三、对象的枚举(遍历)
a: for in
b: hasOwnProperty
c: in
d: instanceof(官方解释A对象是不是B构造函数构造出来的;成哥解释看A对象的原型链上有没有B的原型)
A instanceof B
1 var obj = { 2 height:160, 3 weight:102, 4 sex:‘female‘, 5 grade:100, 6 // __proto__:{ 7 // lastName:‘Fan‘ 8 // } 9 } 10 for(var prop in obj){ 11 // if(obj.hasOwnProperty(prop)){ 12 // console.log(obj[prop]) 13 // } 14 console.log(obj[prop]) 15 }
判断是否是数组的方法
[].constructor //function Array(){}
[] instanceof Array // 返回true
Object.prototype.toString.call([]) //‘[object Array]‘
原文:https://www.cnblogs.com/yqyf/p/12450099.html