原型
在 JavaScript 中,每个构造函数都有一个prototype 属性,这个属性指向函数的原型对象(原型)。使用原型对象的好处是所有对象实例共享它所包含的属性和方法。
什么是原型链?
原型链解决的主要是继承问题。
每个对象拥有一个原型对象,通过__ proto__ ([[Prototype]]) 指针指向创建该对象的构造函数的原型,并从中继承方法和属性,同时原型对象也可能拥有原型,这样一层一层,最终指向 null( Object.proptotype.proto 指向的是null)。这种关系被称为原型链 (prototype chain),通过原型链一个对象可以拥有定义在其他对象中的属性和方法。`
举例说明:
function Person(){
}
Person.prototype.hello = "hello";
Person.prototype.sayHello = function(){
console.log("hello");
}
function Child(){
}
Child.prototype = new Person();
Child.prototype.word = "word";
Child.prototype.sayWord = function(){
console.log("word");
}
let m = new Child()
console.log(m.__proto__ === Child.prototype) // true
console.log(m.__proto__.__proto__ === Person.prototype) // true
console.log(Child.prototype.__proto__ === Person.prototype) // true
console.log(Person.prototype.__proto__ === Object.prototype) // true
// 一切对象都最终继承自Object对象,Object对象直接继承自根源对象null
console.log(Object.prototype.__proto__ === null) // true
Object和Function关系
- Function属性中 prototype属性:它不可写,不可配置,不可遍历。 即它永远指向固定的一个对象,且是其他所有函数的原型对象,所有函数本身的__proto__指向它。
console.log(Person.__proto__ === Function.prototype) // true
console.log(Object.__proto__ === Function.prototype) // true
console.log(Function.__proto__ === Function.prototype) // true
2. 一切对象(包括Function对象)直接继承或最终继承自Object对象。
console.log(Object.prototype === Function.prototype.__proto__)
//true
通过对象字面量等方式创建对象:
- 使用对象字面量创建的对象,其 [[Prototype]] 值是 Object.prototype。
- 使用数组字面量创建的对象,其 [[Prototype]] 值是 Array.prototype。
- 使用 function f(){} 函数创建的对象,其 [[Prototype]] 值是 Function.prototype。
- 使用 new fun() 创建的对象,其中 fun 是由 JavaScript 提供的内建构造器函数之一(Object, Function, Array, Boolean, Date, Number, String 等等),其 [[Prototype]] 值是 fun.prototype。
- 使用其他 JavaScript 构造器函数创建的对象,其 [[Prototype]] 值就是该构造器函数的 prototype 属性。
let o = {a: 1};
// 原型链: o ---> Object.prototype ---> null
let a = ["yo", "whadup", "?"];
// 原型链: a ---> Array.prototype ---> Object.prototype ---> null
function f(){
return 2;
}
// 原型链: f ---> Function.prototype ---> Object.prototype ---> null
let fun = new Function();
// 原型链: fun ---> Function.prototype ---> Object.prototype ---> null
function Foo() {}
let foo = new Foo();
// 原型链: foo ---> Foo.prototype ---> Object.prototype ---> null
function Foo() {
return {};
}
let foo = new Foo();
// 原型链: foo ---> Object.prototype ---> null