以前知道javascript中有for in的用法,可以方便的使用对象中的键值,也知道for in会遍历对象原型中的属性与方法,但是今天用起来发生了一些错误。特此总结备忘。

错误的原因就是对上面红字标注的对象原型没有真正的认识。

对于原型属性(prototype),是只有函数对象(Function)才有的一个属性。

function Person () {}
console.log(Person.prototype);

var p = new Person;
console.log(p.prototype);

说for in会遍历对象原型中的属性与方法,下面的例子引起了我的疑问:

//Person constructor
function Person () {};

//static function of Person
Person.staticFn = function () {
console.log('Person.staticFn');
};

//add method to Person prototype
Person.prototype.eat= function () {
console.log('Person.prototype.eat');
};

//below cause my doubt
for(key in Person){
console.log(Person[key]);
}

上面的代码中,在Person构造函数中添加了一个静态方法staticFn和在prototype属性中添加了一个方法eat,输出的时候并没有遍历到在

prototype中添加的方法eat。

别的资料中对于原型属性(prototype)的定义是:返回对象类型原型的引用。这个属性只有在使用类式继承时才可以体现出作用。有种只能意会不能言传的

感觉。就是开头红字标出的原型,与构造函数中的prototype属性不是同一个东西。简单的说Person函数对象的原型其实是一个Native Function

对象(不是prototype),而那个Native Function的原型是一个Native Object对象。

------------------------------------------------------------------------------------------------------------------------------------

下面的几个例子可能会让问题明朗:

function Person () {
this.privilegedFn = function () {
console.log('Person.privilegedFn');
};
}

Person.staticFn = function () {
console.log('Person.staticFn');
};

Person.prototype.eat = function () {
console.log('Person.prototype.eat');
};

var p = new Person;

for(key in p){
p[key]();
}

console.log('------------------------------------------------');

//and this
Function.prototype.fpf = function () {
console.log('Function.prototype.fpf');
};

for(key in Person){
Person[key]();
}



Posted on 2012-03-22 00:43  ordinary hsiao  阅读(211)  评论(0)    收藏  举报