js原型与原型链

一、普通对象与函数对象

var o1 = {}; 
var o2 =new Object();
var o3 = new f1();

function f1(){}; 
var f2 = function(){};
var f3 = new Function('str','console.log(str)');

console.log(typeof Object); //function 
console.log(typeof Function); //function  

console.log(typeof f1); //function 
console.log(typeof f2); //function 
console.log(typeof f3); //function   

console.log(typeof o1); //object 
console.log(typeof o2); //object 
console.log(typeof o3); //object

在上面的例子中 o1 o2 o3 为普通对象,f1 f2 f3 为函数对象。

凡是通过 new Function() 创建的对象都是函数对象,其他的都是普通对象。f1,f2,归根结底都是通过 new Function()的方式进行创建的。Function Object 也都是通过 New Function()创建的

二、构造函数

function Person(name, age, job) {
 this.name = name;
 this.age = age;
 this.job = job;
}
var person1 = new Person('peng', 28, 'Software Engineer');
var person2 = new Person('Mick', 23, 'Doctor');

person1和person2都是Person的实例,这两个实例都有constructor属性,该属性为一指针,指向Person(因为实例上并没有constructor属性,所以实际上是通过原型链找到原型对象上constructor属性,且原型对象上的constructor属性是指向构造函数的,当我们重写了原型对象后,如果新的原型对象失去了constructor属性,则会在原型链上继续寻找constructor属性,这时实例.constructor就不会指向原来的构造函数了),即

person1.constructor == Person  // true
person2.constructor == Person  // true

重点:实例的构造函数属性(constructor)指向构造函数

三、原型对象

每个函数对象都有一个prototype 属性,这个属性指向函数的原型对象。

function Person() {}
Person.prototype.name = 'Zaxlct';
Person.prototype.age  = 28;
Person.prototype.job  = 'Software Engineer';
Person.prototype.sayName = function() {
  alert(this.name);
}
  
var person1 = new Person();
person1.sayName(); // 'Zaxlct'

var person2 = new Person();
person2.sayName(); // 'Zaxlct'

console.log(person1.sayName == person2.sayName); //true

注意点: 

每个对象都有 __proto__ 属性,但只有函数对象才有 prototype 属性

那什么是原型对象呢?如下

Person.prototype = {
   name:  'Zaxlct',
   age: 28,
   job: 'Software Engineer',
   sayName: function() {
     alert(this.name);
   }
}

 原型对象实则就是一个普通对象,其实Person.prototype还有一个隐藏属性(constructor),该属性(constructor)指向Person,而在前面我们说过,Person的实例对象person1的constructor也指向Person

这里我们可以得到

Person.prototype.constructor == Person
person1.constructor == Person

同理,我们这里可以把Person.prototype看做是Person的实例对象,故Person.prototype的constructor指向Person

结论:原型对象(Person.prototype)是 构造函数(Person)的一个实例。

原型对象其实就是普通对象(但 Function.prototype 除外,它是函数对象,但它很特殊,他没有prototype属性(前面说道函数对象都有prototype属性)

 function Person(){};
 console.log(Person.prototype) //Person{}
 console.log(typeof Person.prototype) //Object
 console.log(typeof Function.prototype) // Function,这个特殊
 console.log(typeof Object.prototype) // Object
 console.log(typeof Function.prototype.prototype) //undefined

原型对象的主要作用是用于继承,通过给 Person.prototype 设置了一个函数对象的属性,那有 Person 的实例(person1)出来的普通对象就继承了这个属性。

四、__proto__

普通对象还有函数对象都有__proto__的内置属性,用于指向创建它的构造函数的原型对象

如上面的person1的实例对象,它也有__proto__属性,它的构造函数为Person

则有 person1.__proto__ == Person.prototype

 

五. 构造器

熟悉 Javascript 的童鞋都知道,我们可以这样创建一个对象:
var obj = {}
它等同于下面这样:
var obj = new Object()

obj 是构造函数(Object)的一个实例。所以:
obj.constructor === Object
obj.__proto__ === Object.prototype

新对象 obj 是使用 new 操作符后跟一个构造函数来创建的。构造函数(Object)本身就是一个函数(就是上面说的函数对象),它和上面的构造函数 Person 差不多。只不过该函数是出于创建新对象的目的而定义的。所以不要被 Object 吓倒。

同理,可以创建对象的构造器不仅仅有 Object,也可以是 Array,Date,Function等。
所以我们也可以构造函数来创建 Array、 Date、Function

var b = new Array();
b.constructor === Array;
b.__proto__ === Array.prototype;

var c = new Date(); 
c.constructor === Date;
c.__proto__ === Date.prototype;

var d = new Function();
d.constructor === Function;
d.__proto__ === Function.prototype;

这些构造器都是函数对象:

 

六. 原型链

  1. person1.__proto__ 是什么?
  2. Person.__proto__ 是什么?
  3. Person.prototype.__proto__ 是什么?
  4. Object.__proto__ 是什么?
  5. Object.prototype__proto__ 是什么?

答案:
第一题:
因为 person1.__proto__ === person1 的构造函数.prototype
因为 person1的构造函数 === Person
所以 person1.__proto__ === Person.prototype

第二题:
因为 Person.__proto__ === Person的构造函数.prototype
因为 Person的构造函数 === Function
所以 Person.__proto__ === Function.prototype

第三题:
Person.prototype 是一个普通对象,我们无需关注它有哪些属性,只要记住它是一个普通对象。
因为一个普通对象的构造函数 === Object
所以 Person.prototype.__proto__ === Object.prototype

第四题,参照第二题,因为 Person 和 Object 一样都是构造函数

第五题:
Object.prototype 对象也有proto属性,但它比较特殊,为 null 。因为 null 处于原型链的顶端,这个只能记住。
Object.prototype.__proto__ === null

七. 函数对象

Number.__proto__ === Function.prototype  // true
Number.constructor == Function //true

Boolean.__proto__ === Function.prototype // true
Boolean.constructor == Function //true

String.__proto__ === Function.prototype  // true
String.constructor == Function //true

// 所有的构造器都来自于Function.prototype,甚至包括根构造器Object及Function自身
Object.__proto__ === Function.prototype  // true
Object.constructor == Function // true

// 所有的构造器都来自于Function.prototype,甚至包括根构造器Object及Function自身
Function.__proto__ === Function.prototype // true
Function.constructor == Function //true

Array.__proto__ === Function.prototype   // true
Array.constructor == Function //true

RegExp.__proto__ === Function.prototype  // true
RegExp.constructor == Function //true

Error.__proto__ === Function.prototype   // true
Error.constructor == Function //true

Date.__proto__ === Function.prototype    // true
Date.constructor == Function //true

所有的构造器都来自于 Function.prototype,甚至包括根构造器ObjectFunction自身。所有构造器都继承了·Function.prototype·的属性及方法。如length、call、apply、bind

 Function.prototype也是唯一一个typeof XXX.prototype为 functionprototype

console.log(typeof Function.prototype) // function
console.log(typeof Object.prototype)   // object
console.log(typeof Number.prototype)   // object
console.log(typeof Boolean.prototype)  // object
console.log(typeof String.prototype)   // object
console.log(typeof Array.prototype)    // object
console.log(typeof RegExp.prototype)   // object
console.log(typeof Error.prototype)    // object
console.log(typeof Date.prototype)     // object
console.log(typeof Object.prototype)   // object

console.log(Function.prototype.__proto__ === Object.prototype) // true
这说明所有的构造器也都是一个普通 JS 对象,可以给构造器添加/删除属性等。同时它也继承了Object.prototype上的所有方法:toString、valueOf、hasOwnProperty等。

八、prototype

当我们创建一个函数时:

var Person = new Object()
PersonObject 的实例,所以 Person 继承Object 的原型对象Object.prototype上所有的方法:

Object的实例对象都可以具有以上方法,从这里我们也可以看出,Person上的constructor属性是从这里继承来的 

当我们创建一个数组时:

var num = new Array()
num 是 Array 的实例,所以 num 继承Array 的原型对象Array.prototype上所有的方法:

我们可以用一个 ES5 提供的新方法:Object.getOwnPropertyNames
获取所有(包括不可枚举的属性)的属性名不包括 prototy 中的属性,返回一个数组:

var arrayAllKeys = Array.prototype; // [] 空数组
// 只得到 arrayAllKeys 这个对象里所有的属性名(不会去找 arrayAllKeys.prototype 中的属性)
console.log(Object.getOwnPropertyNames(arrayAllKeys)); 
/* 输出:
["length", "constructor", "toString", "toLocaleString", "join", "pop", "push", 
"concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", 
"some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", 
"entries", "keys", "copyWithin", "find", "findIndex", "fill"]
*/

 Object.getOwnPropertyNames(arrayAllKeys) 输出的数组里并没有 constructor/hasOwnPrototype对象的方法,但是定义的数组也可以使用constructor等方法

var num = [1];
console.log(num.hasOwnPrototype()) // false (输出布尔值而不是报错)

因为Array.prototype 虽然没这些方法,但是它有原型对象(__proto__):

// 上面我们说了 Object.prototype 就是一个普通对象。
Array.prototype.__proto__ == Object.prototype

所以 Array.prototype 继承了对象的所有方法,当你用num.hasOwnPrototype()时,JS 会先查一下它的构造函数 (Array) 的原型对象 Array.prototype 有没有有hasOwnPrototype()方法,没查到的话继续查一下 Array.prototype 的原型对象 Array.prototype.__proto__有没有这个方法

当我们创建一个函数:

var f = new Function("x","return x*x;");
//当然你也可以这么创建 f = function(x){ return x*x }
console.log(f.arguments) // arguments 方法从哪里来的?
console.log(f.call(window)) // call 方法从哪里来的?
console.log(Function.prototype) // function() {} (一个空的函数)
console.log(Object.getOwnPropertyNames(Function.prototype)); 
/* 输出
["length", "name", "arguments", "caller", "constructor", "bind", "toString", "call", "apply"]
*/

 我们枚举出了它的所有的方法,所以所有的函数对象都能用,比如:

  JS 内置构造器:

var obj = {name: 'jack'}
var arr = [1,2,3]
var reg = /hello/g
var date = new Date
var err = new Error('exception')
 
console.log(obj.__proto__ === Object.prototype) // true
console.log(arr.__proto__ === Array.prototype)  // true
console.log(reg.__proto__ === RegExp.prototype) // true
console.log(date.__proto__ === Date.prototype)  // true
console.log(err.__proto__ === Error.prototype)  // true

自定义的构造器,这里定义了一个 Person

function Person(name) {
  this.name = name;
}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true

 以下打印结果也是恒等的:

function Person(name) {
    this.name = name
}
// 修改原型
Person.prototype.getName = function() {}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // true

 如果换一种方式设置原型,结果就有些不同了:

function Person(name) {
    this.name = name
}
// 重写原型
Person.prototype = {
    getName: function() {}
}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // false
console.log(p.constructor)  // 打印出的是Object构造函数,而不是Person

// 因为constructor属性是从原型对象上继承来的,而在上面我们把Person的原型对象重新赋值,
// 导致了constructor丢失了,则会去Object上找到constructor属性,则会指向Object构造函数

 js重写原型

function Person(){}
Person.prototype = {
   constructor:Person,
   name:"Nic",
   age:"29",
   sayName:function(){
       alert(this.name)
   }
};
var friend1 = new Person();    //实例在这里
    
friend1.sayName();    // Nic
    

 

function Person(){}
var friend1 = new Person();    //实例在这里
Person.prototype = {
   constructor:Person,
   name:"Nic",
   age:"29",
   sayName:function(){
       alert(this.name)
   }
};

    
friend1.sayName();    // 报错

// 因为__proto__ 还是指向原来的原型对象
friend1.__proto__.sayName = function(){
    console.log("peng")
}
friend1.sayName(); // peng
    

第一段重写后再创建实例,此时实例指向改写后的原型对象,所以能调用到原型中的sayName()。

第二段创建实例后再重写,此时实例还是指向刚开始的原型对象。重写原型对象后会将 之前原型对象 的属性和方法全部清除,所以实例访问不到sayName()。 

 十、原型链

function Person(){}
var person1 = new Person();
console.log(person1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype) //true
console.log(Object.prototype.__proto__) //null

Person.__proto__ == Function.prototype; //true
console.log(Function.prototype)// function(){} (空函数)

var num = new Array()
console.log(num.__proto__ == Array.prototype) // true
console.log( Array.prototype.__proto__ == Object.prototype) // true
console.log(Array.prototype) // [] (空数组)
console.log(Object.prototype.__proto__) //null

console.log(Array.__proto__ == Function.prototype)// true

 疑惑:

Function.prototype.__proto__ === Object.prototype //true

因为前面我们说过,Function.prototype比较特殊,是一个函数对象,理论来说,右边应该Function.prototype,所以这里我也是比较疑惑的,但自己指向自己好像没什么意义,JS一直强调万物皆对象,函数对象也是对象,给他认个祖宗,指向Object.prototypeObject.prototype.__proto__ === null,保证原型链能够正常结束。

十一、总结

  • 原型和原型链是JS实现继承的一种模型。
  • 原型链的形成是真正是靠__proto__ 而非prototype
var animal = function(){};
 var dog = function(){};

 animal.price = 2000;
 dog.prototype = animal;
 var tidy = new dog();
 console.log(dog.price) //undefined
 console.log(tidy.price) // 2000

 这里解释一下,就是tidy的__proto__是指向dog.prototype的,所以tidy.price可以访问到,而dog上面并没有price属性,而dog.__proto__是指向Function.prototype的,上面并没有price属性,直到null为止

 var dog = function(){};
 var tidy = new dog();
 tidy.price = 2000;
 console.log(dog.price); //undefined

实例(tidy)和 原型对象(dog.prototype)存在一个连接。不过,要明确的真正重要的一点就是,这个连接存在于实例(tidy)与构造函数的原型对象(dog.prototype)之间,而不是存在于实例(tidy)与构造函数(dog)之间

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值