Home  >  Article  >  Web Front-end  >  javascript 中__proto__和prototype详解_基础知识

javascript 中__proto__和prototype详解_基础知识

WBOY
WBOYOriginal
2016-05-16 16:30:291214browse

__proto__是内部原型,prototype是构造器原型(构造器其实就是函数)

构造器的原型(prototype)是一个对象

那什么是构造器呢?
要想创建一个对象,首先要有一个对象构造器,就像php里面一样,要想创建一个对象,首先要有一个类
构造器的实质就是一个函数,下面的问题是:如何通过这个构造器来创建一个对象呢?
答案: new

构造器构造的是对象。
一、所有构造器/函数的__proto__都指向Function.prototype,它是一个空函数(Empty function)

复制代码 代码如下:

Number.__proto__ === Function.prototype 
// true
Boolean.__proto__ === Function.prototype
// true
String.__proto__ === Function.prototype 
// true
Object.__proto__ === Function.prototype 
// true
Function.__proto__ === Function.prototype
// true
Array.__proto__ ===
Function.prototype  
// true
RegExp.__proto__ === Function.prototype 
// true
Error.__proto__ ===
Function.prototype  
// true
Date.__proto__ ===
Function.prototype   
// true

说明了Number等都是构造器,这些构造器其实是Function的一个对象。 也就是说相当于 var Number = new Function();

JavaScript中有内置(build-in)构造器/对象共计12个(ES5中新加了JSON),这里列举了可访问的8个构造器。剩下如Global不能直接访问,Arguments仅在函数调用时由JS引擎创建,Math,JSON是以对象形式存在的,无需new。它们的__proto__是Object.prototype。如下

复制代码 代码如下:

Math.__proto__ === Object.prototype 
// true
JSON.__proto__ === Object.prototype 
// true

上面说的“所有构造器/函数”当然包括自定义的。如下

复制代码 代码如下:

// 函数声明
function Person()
{}
// 函数表达式
var Man
=
function()
{}
console.log(Person.__proto__ === Function.prototype)
// true
console.log(Man.__proto__ ===
Function.prototype)   
// true

这说明什么呢?

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

Function.prototype也是唯一一个typeof XXX.prototype为 “function”的prototype。其它的构造器的prototype都是一个对象。如下

复制代码 代码如下:

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

噢,上面还提到它是一个空的函数,alert(Function.prototype) 下看看。

知道了所有构造器(含内置及自定义)的__proto__都是Function.prototype,那Function.prototype的__proto__是谁呢?

相信都听说过JavaScript中函数也是一等公民,那从哪能体现呢?如下

复制代码 代码如下:

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

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

最后Object.prototype的__proto__是谁?

复制代码 代码如下:

Object.prototype.__proto__ ===
null  //
true

已经到顶了,为null。

大家是否对javascript 中__proto__和prototype之间的区别联系有所了解了呢,有疑问就留言,大家共同探讨吧

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn