# 4.原型、原型链
# 原型 prototype
var function Abc() {} ,则构造函数在成立时就有一个自带属性:Abc.prototype = {} ,可以认为这个属性是构造函数构造的对象的爹!
定义:原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过该构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。
利用原型特点和概念,可以提取共有属性
对象如何查看原型 ————> 隐式属性: proto 。
- proto 可以供被构造出的对象查看自己的 prototype(原型)
对象如何查看本身的的构造函数 ————> construtor
- construtor 是 prototype 自带的一个属性,供于被构造出的对象查找自己的构造函数。因为是属性,所以可以改变 construtor 的属性值
# 原型链
原型链的链接点是__proto__ 原型链的最终是 Object.prototype ,是所有对象的最终原型!
原型链的 增 删 改 查 与原型基本一致 原型链不同的对象可以修改对方的属性,但只能调用式的修改,不能赋值式的修改
Object.create() 这种方法也可以创建对象。括号里面书写创建的对象的原型。 var obj = {name : 'sunny', age : 123}; var obj1 = Object.create(obj); 此时obj1的原型是obj
绝大多数对象的最终都会继承自Object.prototype Object.create(null) 构建出来的对象没有原型,所以不可能继承 Object.prototype
# call/apply
借用别人的函数实现自己的功能
call 和 apply 的功能 :改变 this 指向
var obj = {};
function Person(name, age) {
//this == obj;
this.name = name;
this.age = age;
this.color = 'green';
}
var person = new Person('deng', 100);
Person.call(obj, 'cheng', 300);
此处的obj借用了Person的方法,把 Person.name 在自己的对象内转换成 obj.name obj 和 person 不一样,obj 不是 Person 的构造品。
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade) {
// var this = {};
Person.call(this, name, age, sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny', 123, 'male', 139, 2017);
此处的 call 执行的操作相当于把 Person 里的方法,复制到 Student 的对象 this = {} 里面
- apply 和 call 的区别 call 需要把实参按照实参的个数传进去,apply 需要传一个 arguments(数组) 进去。即两者的传参列表不同
function Wheel(wheelSize, style) {
this.wheelSize = wheelSize;
this.style = style;
}
function Sit(c, sitColor) {
this.c = c;
this.sitColor = sitColor;
}
function Model(height, width, len) {
this.height = height;/.
this.width = width;
this.len = len;
}
function Car(wheelSize, style, c, sitColor, height, width, len) {
Wheel.call(this, wheelSize, style);
Sit.call(this, c, sitColor);
Model.apply(this, [height, width, len]);
}
var car = new Car(100, '花里胡哨的', '真皮', 'red', 1800, 1900, 4900);
call 和 apply 的使用格式,都是需要借用的模板的 函数名.call/apply