与 Function 和 Object 前世今世的关系

object其实是function Object()的一个实例对象。
看图做几个题。。
function Foo() {};
var foo = new Foo();
alert(foo instanceof Foo); // true
alert(foo instanceof Object); // true
alert(foo instanceof Function); // false
alert(Foo instanceof Function); // true
alert(Foo instanceof Object); // true
在看。。
alert(Object.forEach); // undefined
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
alert(Object.forEach);
alert(Function.forEach);
alert(Object.forEach === Function.forEach); // true
__proto__指向的是其构造函数的原型对象。需要注意的是,这个 __proto__ 只存在于函数实例与构造函数的原型函数之间,而非实例与构造函数之间。
详细解释在:http://www.mollypages.org/misc/js.mp
如果上面的路径不能访问,看下面的几个例子。。摘自上文
Viewing/following various arrows in the diagram above, you'll see some interesting relationships in the core javascript language. (Type these code examples in a javascript console if you want to play along).
- Function.__proto__ points to Function.prototype. This results in:
Function.constructor === Function
That is to say: Function is it's own constructor ! - Object instanceof Object == true.
This is because:
Object.__proto__.__proto__.constructor == Object
Note also that unlike
Object instanceof Object, Foo instanceof Foo == false.This is because: Foo does not exist as a constructor for it's own prototype chain.
- Function.prototype.toString is a built-in method and is distinct from another built-in method: Object.prototype.toString
f1.toString() finds: Object.prototype.toString We get something like: [object ...]Whereas:Foo.toString() first finds & uses: Function.prototype.toString() We get something like: [Function foo...]
If we say:delete Function.prototype.toString Foo.toString() We get something like: [object ...]
浙公网安备 33010602011771号