原型,原型链,call/apply
原型
- 定义:
原型是function对象的一个属性,它定义了构造函数制造出的对象的共同祖先。
通过该构造函数产生的对象,可以继承该原型的属性和方法。
原型也是对象
- 利用原型的特点和概念,可以提取共有属性。
Student.prototype.school = '一中';
function Student(age,name,sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
var stu1 = new Student(18,'李华','male');
var stu2 = new Student(19,'小明','male');
var stu3 = new Student(17,'李四','female');
- stu1,stu2,stu3具有公共的属性school : ‘一中’
- 对象如何查看原型:隐式属性proto
function Student(age,name,sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
var stu1 = new Student(18,'李华','male');
Student.prototype.school = '一中';
Student.prototype.sex = 'female';
- 当访问stu1.school时,会显示’一中’;
- 但是当访问stu1时,会显示Student {age: 18, name: ‘李华’, sex: ‘male’},并不存在’school’属性
- 当Student.prototype中与Student这个构造函数中的属性出现冲突时,以Student中的值为主。
function Student(age,name,sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
Student.prototype = {
school : '一中',
hometown : '西安',
}
var stu1 = new Student(18,'李华','male');
var stu2 = new Student(19,'张三','male');
- Student.prototype也可以是一个对象
原型链
- 如何构成原型链
Grand.prototype.lastname = 'James';
function Grand() { }
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'Mike';
}
var father = new Father();
Son.prototype = father;
function Son() {
this.name = 'Mary';
}
var son = new Son();
- 当访问son.lastname时,虽然son没有lastname属性,但是依据原型链,会找到lastname属性,并得到’James’,同样地,访问father.lastname时,也会得到’James’
- 原型链上的增删改查
- 增
function Father() {
this.name = 'Mike';
this.money = {
before : 500,
now : 600,
}
}
var father = new Father();
Son.prototype = father;
function Son() {
this.name = 'Mary';
}
var son = new Son();
son.money.after = 900;
// 相当于
// function Father() {
// this.name = 'Mike';
// this.money = {
// before : 500,
// now : 600,
// after : 900
// }
// }
- 删
每个对象只能删除自己的属性,运用delete,无法删除自己祖先的属性
- 改
function Father() {
this.name = 'Mike';
this.money = {
before : 500,
now : 600,
after : 1
}
}
var father = new Father();
Son.prototype = father;
function Son() {
this.name = 'Mary';
}
var son = new Son();
son.money.after = 900;
此时将son.money.after的值改为900
- 查
直接访问某个属性
- 绝大多数对象最终都会继承自Object.prototype
- Object.create(原型)
- 当时用Object.create(null)时,返回的对象中并没有prototype
call/apply
- 作用:改变this的指向
function Person(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var person = new People('Mike',19,'male',180,75);
function People(name,age,sex,height,weight) {
Person.call(this, name, age, sex),
this.height = height,
this.weight = weight
}
- 当执行函数People的时候,在函数内,会执行一遍Person函数,将Person函数中的this替换为People,当程序运行完的时候,person中就会含有(name,age,sex,height,weight)这五个属性
- 区别:后面传的参数形式不同
- apply传递参数后面的类型应为数组形式,而call后面的参数类型就为属性名