最高半折刷qq各种业务和钻(家里人自己开的,尽管放心,大家多捧捧场)

sking7

导航

JavaScript和instanceof

这里有张讲解prototype的图:http://www.mollypages.org/misc/js.mp

MSN中关于new是这么描述的https://developer.mozilla.org/en/JavaScript/Reference/Operators/new

Syntax

new constructor[([arguments])]

Parameters

constructor
    A function that specifies the type of the object instance.
arguments
    A list of values that the constructor will be called with.
Description

Creating a user-defined object requires two steps:

Define the object type by writing a function.
Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name and properties. An object can have a property that is itself another object. See the examples below.

When the code new foo(...) is executed, the following things happen:

1.A new object is created, inheriting from foo.prototype.
2.The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
3.The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an ob ject, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
 

下面是对insanceof的描述

 

在javascript里,每个function都有一个prototype属性,这个属性的用途是实现继承机制。必如下面定义的function class1:
function class1(){}
class1.prototype = {a:10,b:100};
则class1的每个实例都会从prototype继承a和b这两个属性。

同时,每个对象都会有一个内部的属性_proto_(不同的javascript虚拟机实现用的名字可能不同),这个属性对js开发人员不可见,只在虚拟机内部使用。每当创建一个对象的时候,这个对象的_proto_就会被赋值为这个对象的构造函数的prototype,这样对象的_proto_属性和构造函数的prototype引用相同的对象,并且一旦对象创建完成,_proto_属性就不会改变。 这样通过对象的_proto_属性,以及_proto_所引用的对象的_proto_属性,就构成了一个_proto_链。 当访问一个对象的属性和方法的时候,js虚拟机正是通过这个_proto_链来查找的。

关于instanceof:
假设有一条这样的语句:
o instanceof c;
在上面的语句执行过程中,虚拟机会把c.prototype和o的_proto_链上的节点逐个进行比较,如果找到相等的节点,则返回true,否则返回false。

posted on 2012-01-06 10:12  G.N&K  阅读(284)  评论(0编辑  收藏  举报