- JavaScript的任何函数都是有
Function
构造函数实例化而来;
-
任何函数都是
Function
的实力对象function Person() {}; console.log(Person.__proto__ === Function.prototype); //true console.log(Object.__proto__ === Function.prototype); //true console.log(Array.__proto__ === Function.prototype); //true console.log(String.__proto__ === Function.prototype); //true console.log(Boolean.__proto__ === Function.prototype); //true console.log(Number.__proto__ === Function.prototype); //true console.log(Date.__proto__ === Function.prototype); //true
-
JavaScript的内置对象,本质上都是构造函数;
-
Math
对象是个例外,它是Object
的实例对象console.log(Math.__proto__ === Function.prototype); //false console.log(Math.__proto__ === Object.prototype); //true
-
Math
对象的原型链示例const math = Math.ceil(0.45); console.log(math); // 1 console.log(math.__proto__ === Math.prototype); //false console.log(Math.__proto__ === Object.prototype); //true console.log(Object.prototype.__proto__); //null
-
Math
只是Object
的实力对象,本身不是构造函数,所以没有prototype
原型对象; -
Object.prototype.__proto__
=null
,说明Object处于原型链的顶层;
-
Array为例演示原型链的关系
const array = new Array(); array[0] = 1; array[1] = 2; array[2] = 3; console.log(array); //[1,2,3] console.log(array.__proto__ === Array.prototype); // true console.log(array.prototype); // undefined //`Array.prototype`原型对象是`Object`构造函数的实例 console.log(Array.prototype.__proto__ === Object.prototype); //true console.log(Array.__proto__ === Object.prototype); //false
-
Array原型对象是Object构造函数的实例;
-
Array
本身也是一个构造函数,它实例化了一个array
;
7. 扩展
- 目的: 通过原型链的关系了解实例对象与原型之间的关系
-
创建一个
Person
构造函数function Person({name,age,gender}) { this.name = name, this.age = age, this.gender = gender }
-
实例化对象
const person = new Person({name: "Andy",age: 20,gender: "male"}); console.log(person);
-
在Person构造函数的上一层级构造函数,创建一个属性
Object.prototype.favorite = "Bar"
-
通过原型链查找
favorite
属性console.log(Person.prototype.__proto__.favorite); //"Bar" console.log(person.__proto__.__proto__.favorite); //"Bar"
-
person
实例对象通过其原型对象__proto__
指向其构造函数Person
的原型对象prototype
; -
prototype
本身也具有一个原型对象__proto__
,指向其上一级的构造函数Object
的原型对象prototype
; -
prototype
创建了一个favorite
属性,通过这个原型链关系,可以访问原型链上的所有属性; -
检查
Object.prototype.__proto__
是否存在上一级构造函数的原型对象? null: 表示没有;console.log(Object.prototype.__proto__); // null
-
为了实现代码的复用与继承,开发中总是尽量把共享属性放置与
prototype
原型对象中,而把私有属性,放置在实力对象中;function Animale({name,age,gender}) { this.name = name, this.age = age, this.gender = gender } const person = new Animale({name: "Andy",age: 20,gender: "male"}); const dog = new Animale({name: "Dog",age: 2,gender: "female"}); Animale.prototype.name = "Jhon"; console.log(person); console.log(dog); console.log(Animale.prototype.name); // "Jhon" console.log(Animale.prototype.name); // "Jhon"