简体   繁体   中英

Why dot notation failed in my property access?

I'm learning from the book: Javascript the good parts. And I came across the following code augmenting function definitions.

Function.prototype.method = function(name, func){
    this.prototype[name] = func;
    return this;
};

However, if I replace this.prototype[name] with this.prototype.name there is an error from Firebug, and I was wondering where is the mistake? Thank you for your help in advance.

this.prototype.name等效于this.prototype["name"]而不是this.prototype[name]

you are trying to access the property name from this.prototype , where name is a variable. If you used dot notation it would try to look up the literal string 'name' as a property of the Function.prototype and of course cant find it. Use [name] if the property name is a variable.

In the dot case, name is treated literally, and it is not defined in your case. On the contrary, the name in the brackets are treated as a reference to a string Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM