1、原型及原型链
构造函数:prototype 程序员
实例对象:__proto__ 浏览器 (指向原型对象)
原型对象:prototype construction 属性 方法 (在构造函数中)
原型链:实例对象与原型对象关系,关系通过原型来联系(__proto__)
2、原型指向
构造函数中this是实例对象,原型对象中方法中this是实例对象
实例对象__proto__----->构造函数的prototype(的__proto__)---->object.prototype(的__proto__是null)
3、原型指向改变添加方法
如果原型指向改变,应该在原型改变指向之后添加原型方法
function Person(age){this.age=age;}
//指向改变
Person.prototype={
eat:function(){console.log("吃");}
};
//添加原型方法
Person.prototype.sayHi=function(){console.log("haha");};
var per=new Person(10);
per.sayHi();
4、实例对象与原型对象重名
实例对象访问属性,先从实例对象找,找到直接用,找不到去指向的原型对象中找,找到就使用,找不到是undefined
5、借用原型继承
//动物构造函数
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
//动物原型方法
Animal.prototype.eat=function(){
console.log("吃");
}
//狗的构造函数
function Dog(color){
this.color=color;
}
Dog.prototype=new Animal("萨摩","30kg");
Dog.prototype.bitePerson=function(){
console.log("咬人");
};
//哈士奇
function ErHa(sex){
this.sex=sex;
}
ErHa.prototype=new Dog("黑白");
ErHa.prototype.playHost=function(){
console.log("玩");
};
var erHa=new ErHa("雄");
console.log(erHa.name,erHa.weight,erHa.color);
erHa.eat();
erHa.bitePerson();
erHa.playHost();
6、借用构造函数:构造函数名字.call(当前对象,属性,属性...);
function Person(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
}
Person.prototype.sayHi=function(){
console.log(""你好);
};
function Student(name,sex,age,score){
//借用构造函数
Person.call(this,name,sex,age);
this.score=score;
}
var stu1=new Student("小明","男",10,"100");
console.log(stu1.name,stu1.sex,stu1.age,stu1,score);
var stu2=new Student("小红","女",20,"200");
console.log(stu2.name,stu2.sex,stu2.age,stu2,score);
var stu3=new Student("小力","男",30,"300");
console.log(stu3.name,stu3.sex,stu3.age,stu3,score);
7、组合继承:原型继承+借用构造函数继承
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
Person.prototype.sayHi=function(){
console.log("你好");
};
function Student(name,age,sex,score){
//借用构造函数解决属性值重复
Person.call(this,name,age,sex);
this.score=score;
}
Student.prototype=new Person();
Student.prototype.eat=function(){
console.log("吃");
};
var stu=new Student("小明",20,"男","100");
console.log(stu.name,stu.age,stu.sex,stu.score);
stu.sayHi();
stu.eat();
8、拷贝继承
function Person(){
}
Person.prototype.name="小明";
Person.prototype.age=10;
Person.prototype.sex="男";
Person.prototype.play=function(){console.log("玩");};
var obj2={ };
for(var key in Person.prototype){
obj2[key]=Person.prototype[key];
}
9、函数中this指向
(1)普通函数中this:window
function f1(){console.log(this);}
f1();
(2)对象,方法中this:当前的实例对象
(3)定时器方法中this:window
window.setInterval(function(){console.log(this);},1000);
(4)构造函数中this:实例对象
function Person(){console.log(this);}
var per=new Person();
console.log(per);
(5)原型对象方法中this:实例对象
(6)严格模式:"use strict";
10、函数调用
普通函数:直接调用
构造函数(首字母大写):通过new调用
对象方法:函数.方法
11、函数是对象,对象不一定是函数
对象中有__proto__,是对象
函数中prototype,是对象
既有prototype又有__proto__,既是函数也是对象
12、数组函数调用
var arr=[];
arr.forEach(function(ele){
ele();
});