继承模式
1.传统形式——> 原型链
过多的继承了没有用的属性
Grand.prototype.lastName = "Ji";
function Grand(){ }
var grand = new Grand();
Father.prototype = grand();
function Father(){ }
var father =new Father();
Son.prototype =father;
function Son (){ }
2.借用构造函数
不能继承借用构造函数的原型
每次构造函数都要多走一个函数
function Person (name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Student (name,age,sex,grade){
Person.call(this,name,age,sex);
this.grade = grade;
}
var student = new Student()
3.共享原型
不能随便改变自己的原型,两者互相影响
Father.prototype.Name = "David";
function Father(){ }
function Son(){ }
function inherit (Target,Origin){
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
Son.prototype.sex = "male"; //此时Son,Father的prototype指向同一个prototype, //如果给Son.prototype添加属性,Father.prototype也能访问
var son = new Son();
var father = new Father();
4.圣杯模式
在共享原型的基础上,改变了继承形式
既能共享原型,又能改变其中一个原型的属性,互不影响,
Father.prototype.Name = "David";
function Father(){ }
function Son(){ }
function inherit (Target,Origin){
function F(){};
F.prototype = Origin.prototype
Target.prototype =nae F();
Target.prototype.constructor = Target;//使自己的构造函数归位
Target.prototype.uber = Origin.prototype;//指向超类
}
inherit(Son,Father);
Son.prototype.sex = "male";
var son = new Son();
var father = new Father();
Father.prototype.Name = "David";
function Father(){ }
function Son(){ }
function inherit (Target,Origin){ function F(){};
F.prototype = Origin.prototype Target.prototype =nae F();
Target.prototype.constructor = Target;//使自己的构造函数归位
Target.prototype.uber = Origin.prototype;//超类
}
var inherit = (function (){
var F = function (){};
return function (Target,Origin){
F.prototype = Origin.prototype
Target.prototype =nae F();
Target.prototype.constructor = Target;//使自己的构造函数归位
Target.prototype.uber = Origin.prototype;//超类
} }());
命名空间
管理变量 ,防止污染全局,适用于模块化开发
var init = (function (){
var name = 'abc';
function callName(){
console.log(name);
}
return function (){
callName();
} }())
var init1 =(function (){
var name = 123;
function callName (){
console.log(name);
}
return function (){
callName();
} }())
对象枚举
for in 循环
遍历对象属性个数
通过对象的属性个数来控制循环,
var obj = { id : 0,
name : 'david',
age : 19,
gender : 'male'
}
for(var prop in obj){
console.log(obj[prop]);
} 1. hasOwnproperty方法 //判断对象的属性是否是自己的属性和方法(不包括原型)
var obj = {
id : 0,
name : 'david',
age : 18,
gender : 'male'
__proto__ : {
lastName : 'wang'
} }
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
console.log(obj[prop]);
} }
2. in 操作符 // 判断属性和方法是否是自己的(包括原型)
3. instanceof 操作符
A instanceof B
//A对象 是不是 B构造函数构造出来的
//A对象的原型链 有没B 的原型
浙公网安备 33010602011771号