Jennifer Massey
Jennifer Massey

Reputation: 173

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.

Upvotes: 0

Views: 90

Answers (3)

B.T Gutsu
B.T Gutsu

Reputation: 146

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.

Upvotes: 1

Joe Fitter
Joe Fitter

Reputation: 1309

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.

Upvotes: 2

Quentin
Quentin

Reputation: 944011

this.prototype.name is equivalent to this.prototype["name"] not this.prototype[name].

Upvotes: 2

Related Questions