原型
js
每一个函数都有一个prototype属性,指向原型对象,
prototype (原型对象)的所有属性和方法,都会被构造函数的实例对象所继承。
因此,我们可以把那些公用的(不变的)的属性和方法,定义在原型对象(prototype)上 。
构造函数 prototype 属性指向与 构造函数实例所创建的对象 的__proto__属性指向的是同一个对象。
原型对象可以向所有实例对象共享他的属性和方法,因此,不用在构造函数中定义对象信息,而是可以直接将这些信息添加到原型中。
let arr = []
console.log('arr.__proto__', arr.__proto__); // Array.prototype
console.log('arr.__proto__ === Array.prototype', arr.__proto__ === Array.prototype); // true
console.log('arr.__proto__.__proto__',arr.__proto__.__proto__); // Object.prototype
console.log('arr.__proto__.__proto__ === Object.prototype',arr.__proto__.__proto__ === Object.prototype); // true
__proto__ => __proto__ => __proto__ => null
[] Array.prototype Object.prototype
[] instanceof Array; // true
{} instanceof Object;// true
******
从 instanceof 能够判断出 [ ].__proto__ 指向 Array.prototype,
而 Array.prototype.__proto__ 又指向了Object.prototype,
最终 Object.prototype.__proto__ 指向了null,标志着原型链的结束。
****因此,[]、Array、Object 就在内部形成了一条原型链
js
instanceof 用来判断 A (实例对象) 是否 是 B (构造函数) 的实例。
instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
Array.isArray() 方法用以确认某个对象本身是否为 Array 类型,而不区分该对象在哪个环境中创建。
js
// 自建构造函数的原型 、 原型链
function Cat() {
}
const kitty = new Cat()
console.log('kitty.__proto__', kitty.__proto__); // Cat 原型对象
console.log('yuan xing lian one', kitty.__proto__.__proto__); // Object.prototype
console.log('yuan xing liang two', kitty.__proto__.__proto__ === Object.prototype); // true
// 实例化后,原型上的构造器会传递到子类上,同样指向的是子类构造函数
console.log('子类的构造器', stud.constructor == Student); // true
js
// 原型链继承
function Person() {
}
Person.prototype.name = 'I love you so much'
function Student() {
}
// 子类的原型等于父类的实例
// 如此继承时,也同样继承了父类的构造器 constructor(父类的构造函数)
// new Person() 的实例对象,是一个构造函数 (Student) 的原型对象,
// 而这个原型对象,同时也是构造函数及其实例对象的原型对象,
// 而它又是另一个构造函数 (Person) 的实例对象
Student.prototype = new Person()
// 一般需要将子类的构造器 (构造函数) 重写回来
// ***Student.prototype.constructor = Student
const stud = new Student()
// 找到 Person 的原型对象上了
console.log('stud name ', stud.name); // 'I love you so much'
// ***以下两项,在重写 Student.prototype.constructor = Student 后为 false
console.log('Student.prototype.constructor', Student.prototype.constructor === Person); // true
console.log('构造器', Student.prototype.constructor === Person.prototype.constructor); // true
// 继承一次,就要比原来多一次, __proto__ (Student不重写constructor时)
console.log('原型链继承后能够点几次',stud.__proto__.__proto__.__proto__ === Object.prototype)// true