James Daly
James Daly

Reputation: 1386

Function.prototype.method what is prototype[name]

I'm trying not to duplicate questions obviously as I have seen some questions/answers regarding Douglas Crockford's Javascript the Good parts book

I understand most of this code

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

Function.method('inherits', function (Parent) {
this.prototype = new Parent( );
return this;
});

var Mammal = function (name) {
this.name = name;
}.method('get_name', function () {
return this.name;
}).method('says', function() {
return this.saying || '';
});

var Cat = function (name) {
this.name = name;
this.saying = 'meow';
}.inherits(Mammal)

var myCat = new Cat('bagsley');
myCat.get_name();

what I'm having trouble getting is the this.prototype[name] why isn't it written as this.prototype.name; I know returning this allows chaining and the syntax here looks very similar to jQuery but I still don't get the prototype[name] part

Any help is apprecaited thanks

Upvotes: 4

Views: 1786

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185933

There is a difference between obj.name and obj[name].

This...

obj.name = 123;

...will assign the value 123 to the "name" property (of the object).

On the other hand, this...

obj[ name ] = 123;

...will assign the value 123 to those property which name is equal to the value of the name variable/argument.

So:

var name = 'foo';

obj.name = 123;
obj[ name ] = 456;

// And now:
obj.name; // 123
obj.foo; // 456

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

prototype[name] allows name to be a variable containing any string, and it will access the property of prototype named by the string. prototype.name would look for the property literally called "name".

The [] syntax allows you to:

  1. Have variable property names - especially useful when looping through properties with for..in
  2. Use symbols in property names that are otherwise disallowed (eg. obj['foo-bar'], arr[123])
  3. Have closer resemblance to the associative arrays of other languages such as PHP.

Upvotes: 2

Related Questions