原型链结构图
代码示例
//01 提供Person构造函数
function Person(name,age) {
this.name = name;
this.age = age;
}
//02 设置Person的原型对象
Person.prototype.showName = function () {
console.log(this.name);
}
//03 创建Student构造函数
function Student(number) {
this.numer = number
}
//04 设置Student的原型对象
Student.prototype = new Person();
原型链图示例
Function.prototype原型链
关于Function和自定义构造函数的原型对象
Function.prototype 是一个空的函数
自定义构造函数的原型对象是一个空的对象
说明
Function也可以被当做是一个构造函数
通过new Function创建出来的函数,可以认为是Function的实例化对象。
Function的原型对象是一个空的函数,这个空的函数也是一个对象,它的原型对象是Object.prototype。
在JS中,Object的原型对象是所有对象的祖宗。
Function是构造函数,则其原型对象为空的函数
空的函数的原型对象为Object.prototype
Function本身也是对象,则其构造函数为:function Function() { [native code] } 是自身
同Object类型
Object本身是构造函数,其原型对象是Object.prototype
Object本身也是对象,其构造函数为:function Function() { [native code]
代码示例
//01 提供Person构造函数
function Person(name,age) {
this.name = name;
this.age = age;
}
//02 设置Person的原型对象
Person.prototype.showName = function () {
console.log(this.name);
}
//03 创建Student构造函数
function Student(number) {
this.numer = number
}
//04 设置Student的原型对象
Student.prototype = new Person();
完整的原型链示意图
Object和Function的关系
01 Object构造函数是通过Function构造函数实例化出来的
02 Function构造函数也是通过Function构造函数实例化出来的
代码示例
//检查对象是否是某个构造函数的实例
console.log(Function instanceof Function);
console.log(Function instanceof Object);
console.log(Object instanceof Object);
console.log(Object instanceof Function);
//注意:以上打印结果均为true