原型链

原型对象

JS原型对象初始化

参考函数建立的简单步骤,以下:javascript

F = new NativeObject();

//第一步:设置Class:function;
F.[[Class]] = "Function"

//第二步:函数对象的隐式prototype指向Function的显示原型, function的prototype也是一个对象, 是Object对象的实例, Object又是由Function构建出来的, 因此能够循环此步骤;
F.[[Prototype]] = Function.prototype

//第三步:初始化
F.[[Call]] = <reference to function>
F.[[Construct]] = internalConstructor

//第四步:初始化当前执行上下文的做用域链
F.[[Scope]] = activeContext.Scope

// 若是函数经过new Function(...)来建立,那么
F.[[Scope]] = globalContext.Scope

//第五步:初始化传入参数的个数
F.length = countParameters

//第六步:F对象建立的原型
__objectPrototype = new Object();
__objectPrototype.constructor = F
F.prototype = __objectPrototype

return F

什么是原型对象

  • 从上面能够看出, 每个构造函数都有一个原型属性, 称为prototype, 它指向一个对象, 这个对象称为原型对象;java

  • 默认全部原型对象自动得到constructor属性;constructor又引用了函数自己,因此也造成了JS中的构造函数和prototype的循环引用;函数

原型对象的问题

  • 原型对象是由全部实例共享,对于包含引用类型值的属性来讲,修改会影响到全部的实例;
  • 原型模式普遍应用于原生的引用类型如Object、Array、String等, 但不推荐在程序中修改原生对象的原型, 容易致使命名冲突;

原型链

通常的解释:this

  • 全部对象均可以有原型,而且原型也是对象,因此接着它们也能够有原型,原型又能够有原型,如此就造成了所谓的原型链。当链条中的对象有一个值为null 的原型时,原型链终止。

ECMA的解释:spa

  • Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.

看了如上中文解释,你确定会困扰吧?是由于它只一味的提到原型; 而没有对隐式的原型 [[prototype]]和显示的prototype进行区分;prototype

因此你可能会认为, 按照第一种解释以下代码先寻找A.prototype, 发现A.prototype = null; 原型链终止,A.toString是否是会报undefined呢?指针

//分析function A的原型链
function A() {}

A.prototype = null;

A.toString();

再看英文解释: Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property;code

很是清晰:对象

  • 全部由构造器建立的对象都有一个隐式的prototype, 它指向构造器的prototype属性
  • 因此原型链实际上是由当前对象的隐式prototype指针指向的对象的隐式prototype指针指向的对象的…., 直到隐式prototype指向的对象为空为至;有点饶;

Object的prototype是null吗?

解释一:Object 构造器的默认原型值为null;blog

解释二:15.2.4 Properties of the Object Prototype Object

    The value of the [[Prototype]] internal property of the Object prototype object is null, the value of the [[Class]] internal property is “Object”, and the initial value of the [[Extensible]] internal property is true.

 

解释一也存在和上面同样的问题,而英文的解释则很是明显:

并不是Object.prototype = null而是function Object中的隐式的prototypenull, 以下:

function Object() {};
var obj = new Object();
obj.[[prototype]] = Object.prototype
Object.prototype.[[prototype]] = null;

示例

看了上述的描述, 若是你彻底理解了显示prototype和隐式prototype,我想你应该会很快n能画出以下对象的原型链了。试试看吧:

示例1:请描述a对象的原型链

var A = function() {};

A.prototype = { b: 2, c: 3 };

var a = new A();

示例二:请描述b对象的原型链

var A = function() {}

A.prototype = { b: 2, c: 3 };

var B = function() {}

B.prototype = new A();

var b = new B();

 

 

相关文章
相关标签/搜索