本文主要讲述的是js中的原型和原型链。
一、构造方法
在将js的原型链之前需要先了解一下js中的构造方法,js中(es5),一个方法function通常就是一个构造方法,通常我们会将这个构造方法的首字母大写
,用new function
来创建一个实例:
function Student(name, age){
this.name = name;
this.age = age;
}
var stu = new Student();
在上面的例子中 Student就可以作为一个构造方法。
二、实例原型
每个函数都有一个prototype
属性,这个属性指向实例原型:
function Student(name, age){
this.name = name;
this.age = age;
}
console.log(Student.prototype);//{constructor: ƒ}
函数的实例有一个__proto__
属性,这个属性指向实例原型:
function Student(name, age){
this.name = name;
this.age = age;
}
var stu = new Student();
console.log(Student.prototype);//{constructor: ƒ}
console.log(stu.__proto__);//{constructor: ƒ}
console.log(Student.prototype == stu.__proto__);//true
实例原型有个constructor
属性,这个属性指向构造函数:
function Student(name, age){
this.name = name;
this.age = age;
}
console.log(Student.prototype.constructor);//ƒ Student(name, age)
构造函数,实例,实例原型,它们三者的关系如下图:
三、原型链
其实__proto__
一层层的指向就是原型链,最终都会指向null,如下图:
当用.
获取对象的属性和方法时,会从对象开始,沿着原型链向上找:
function Student(name, age){
this.name = name;
this.age = age;
}
var stu = new Student();
Student.prototype.type = "student";
console.log(stu.type);//student
四、 Object.create
4.1 语法
Object.create(proto, [propertiesObject])
: 创建一个新对象,使用现有的对象来提供新创建的对象的proto。
4.2 参数
- proto :
必须
。表示新建对象的原型对象
,即该参数会被赋值到目标对象
(即新对象,或说是最后返回的对象)的原型上
。该参数可以是null
,对象
, 函数的prototype
属性 (创建空的对象时需传null
, 否则会抛出TypeError异常)。 - propertiesObject :
可选
。 添加到新创建对象的可枚举属性(即其自身的属性,而不是原型链上的枚举属性
)对象的属性描述符以及相应的属性名称。这些属性对应Object.defineProperties()
的第二个参数
。
4.3 Object.create(null)
通过Object.create(null)
创建的对象是非常纯净
的,原型链的属性和方法都不会携带
。这就非常适合数组对象开发的时候,从对象中取值,提高循环效率。
var obj = Object.create(null) ;
console.log(obj); // 打印可以发现,obj 没有__proto__ 属性