原型
JavaScript 是一种基于原型的语言,每个对象都是原型对象的实例。
每个函数都有一个叫做原型 (prototype) 的属性。可以添加属性到 prototype 上。之后就可以利用new
创造新的、含有这个属性的实例。
var Point = function () {};
Point.prototype.value = [1, 2];
let p = new Point();
console.log(p.value);
//[1, 2]
使用的时候会链式查找是否有这个属性。
继承
定义在 prototype
上的属性(一个对象)可以继承。
var Vehicle = function () {};
Vehicle.prototype.color = "red";
Vehicle.seats = 4;
console.log(Vehicle.color);
//undefined
console.log(Vehicle.seats);
//4
let car = new Vehicle();
console.log(car.color);
//red
console.log(car.seats);
//undefined
console.log(Vehicle);
//function(){ }
console.log(car);
/*{}
<prototype>: {…}
color: "red"
constructor: function Vehicle()*/
Vehicle.color
输出undefined
,car.color
不是, 而Vehicle.seats
可以直接使用。 定义在prototype
上的属性当前对象不能使用,继承对象才能使用。- 需要继承的属性定义在
prototype
上,比如说car
能使用color
而不能使用seats
。 car.__proto__
就是对象Vehicle
。
__proto__
和 prototype
每个实例对象( object )都有一个私有属性(称之为 proto )指向它的构造函数的原型对象(prototype)。
在查找属性是否存在的时候,先查找属性是否存在,不然就查找其 __proto__
中是否存在,然后是 __proto__
指向的对象的 __proto__
中是否存在,直到 __proto__
为 null
。
其他
匿名函数的prototype
:
const cola = () => "Give me cola!";
console.log(cola);
//() => "Give me cola!"
console.log(cola.prototype);
//undefined
console.log(cola.__proto__);
//function () {
// [native code]
//}
参考资料