javascript prototype,executing,context,closure


要学好JavaScript,有几个基本概念必须搞清楚:prototype,executing,context,closure。
Prototype

在JavaScript语言中,通常使用Prototype来实现OO。在这里,我们不对JavaScript的OO实现进行过多的探讨,着重来看一下JS中对象的内存模型。在开始之前,需要先明确以下几点:
1. JS中,存在以下几种数据类型:string,number,boolean,object,function(注意:首字母均为小写)。
2 “Object”, “String”, “Date”等内置数据类型,在JS中实际上是函数名称(使用"alert(typeof Object)"可以验证,输出为"function")。我们通常指的类型为"Date"的数据类型,实际上是通过"new Date"所产生的对象。
3. 在JavaScript中,对象都是associative array (hash table),可以动态指定对象的property。
4. 在Firefox中可以使用"__proto__"属性来查看一个对象的"prototype"。

下面我们来看一个简单的例子:

function Person() { this.age = 10; this.name = "test";}Person.prototype = new Object;var p = new Person;alert(p); // output "[object Object]"alert(p.__proto__); // output "[object Object]"

可以看出Person数据类型具有一个“prototype”,如果更改这个prototype,会影响到所有已经产生的Person类型的对象,同时也会影响到以后建立的Person类型的对象。如果指定一个function的prototype属性,则所有使用该function生成的对象实例中(使用new操作符)都具有该prototype,在Firefox 中,可以使用"__proto__"属性访问。

通常情况下,我们讲JS中的对象都继承Object数据类型,这是如何体现的呢?我们把以上的程序稍微修改一下:

function Person() { this.age = 10; this.name = "test";}var p = new Person;alert(p); // output "[object Object]"alert(p.__proto__); // output "[object Object]"alert(p.__proto__.__proto__); // output "[object Object]"alert(p.__proto__.__proto__ == Object.prototype); // output "true"alert(p.__proto__.__proto__.__proto__); // output "null"

由以上程序可以看到,Person的"prototype"(在这里,没有明确指定Person.prototype, 而是使用缺省值)的"prototype" (p.__proto__.__proto__)正是Object.prototype, Object.prototype是prototype chain的终点(其自己的祖先为null)。

在JS中,Object是function,同时,所有function的实例,也都是Object。请看如下程序:

/* Object, Function都是function数据类型 */alert(typeof Object); // output "function"alert(typeof Function); // output "function"/* Function的prototype是一个空function */alert(Function.prototype); // output "function() {}"alert(Function.__proto__ == Function.prototype); // output "true"/* function是object, 其prototype chain的终点是Object.prototype */alert(Function.__proto__.__proto__ == Object.prototype); //output "true"/* Object是function的实例 */ alert(Object.__proto__ == Function.prototype); // output "true"alert(Object.__proto__.__proto__ == Object.prototype); // output "true"改变Function.prototype会影响到“Object”,改变Object.prototype会影响到所有function的实例。
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3