原型与原型链
js中的原型与原型链
原型(prototype)
- 定义:每个函数在创建时,都会自动拥有一个
prototype
属性,它是一个对象,包含了该函数所创建对象的共享属性和方法。比如内置的Array
构造函数,它的prototype
上就有push
、pop
等方法,所有通过new Array()
创建的数组实例都能访问这些方法。 - 示例:
function Person(name) {this.name = name;
}
Person.prototype.sayHello = function() {console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.sayHello(); // 可以访问原型上的方法
实现代码复用,避免每个实例都重新创建相同的方法,节省内存空间。
//true
- console.log([1, 2, 3] instanceof Object);
//trueconsole.log([1, 2, 3].__proto__.__proto__ === Object.prototype);
从上可知数组是对象
原型链
一条对象及其原型组成的链就叫做原型链。
-
定义:当访问一个对象的属性或方法时,如果该对象自身没有这个属性或方法,JavaScript会自动到它的原型对象中查找;如果原型对象也没有,就会继续到原型对象的原型中查找,这样一层一层向上查找的链路就构成了原型链,直到查找到
Object.prototype
,其原型为null
,查找结束。 -
示例:
function Animal() {this.eat = function() {console.log('eating');};
}
function Dog() {this.bark = function() {console.log('barking');};
}// Dog的原型指向Animal的实例
Dog.prototype = new Animal();
const dog = new Dog();
dog.bark(); // 自身方法
dog.eat(); // 通过原型链找到Animal原型上的方法
实现原型的继承,子类可以通过原型链获取父类的属性和方法。
对象都有__proto__,都指向原型对象。
原型链的顶层
拿person对象来看
// 1. person的原型对象
function person(...){//
}
person.__proto__ === Person.prototype
// 2. Person.prototype的原型对象
Person.prototype.__proto__ === Object.prototype
Object.prototype也是一个对象
Object.prototype.__proto__ === null
原型链 :由对象的__proto__属性串连起来的直到Object.prototype.proto(为null)的链就是原型链。
JavaScript中一切引用类型都是对象,对象就是属性的集合。