原型
每一个函数(function)对象都有一个prototype属性,这个属性指向函数的原型对象。原型对象定义了函数对象(构造函数)创造出的对象的公共祖先。即通过函数对象产生的对象可以继承该原型的属性和方法。
function Person(){
this.name = 'xiaoliu';
this.sex = 'female';
}
console.log(Person);
console.log(Person.prototype);
可以看出Person为函数对象,而它的prototype属性为普通对象。原型对象中有两个属性:
- constructor
指向原型对象所属的函数对象(即Person.prototype.constructor === Person) - prototype
原型对象也是对象所以它也有对应的prototype。(绝大多数对象最终都会继承Object.prototype)。
但是Object的prototype.__proto__为空
(Object.prototype.proto === null // true)
对象查看原型
对象通过隐式属性__proto__。
console.log(person.__proto__ === Person.prototype); //true
可以利用prototype给对象增加属性
function Person(){
this.name = 'xiaoliu';
this.sex = 'female';
}
var person = new Person();
person.__proto__.age = 18;
console.log(person.age); //18
原型链
通过原型链可以实现继承。
function Person(){
this.name = 'xiaoliu';
this.sex = 'female';
}
function Student(){
this.school = 'college';
}
Student.prototype = new Person(); //将、Student的原型对象设置为Person,实现继承
var student = new Student();
var person = new Person();
conslo.log(student.name);
console.log(student.sex);
函数对象的call()、apply()方法
所有构造器(含内置及自定义)的__proto__都是Function.prototype。所以都能使用call()、apply()方法。
这两个方法主要用于调换this指向。第一个参数为object 为要指向的目标。call从第二个参数开始传原来函数的参数,而apply第二个参数为一个参数数组。
function Bed(size){
this.size = size;
}
function Sofa(width, length){
this.width = width;
this.length = length;
}
function Bedroom(bedSize, sofaWidth, sofaLength){
// Bed.call(this,bedSize);
// Sofa.call(this,sofaWidth, sofaLength);
Bed.apply(this,[arguments[0]]);
Sofa.apply(this,[arguments[1],arguments[2]]);
}
var bedRoom = new Bedroom(1,3,4);
console.log(bedRoom);