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
2 Answers 2
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
5 Comments
this.prototype.frank? The method method will not work properly if it's defined like that. It has to be this.prototype[name], so that the argument value is used for the name...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:
- Have variable property names - especially useful when looping through properties with
for..in - Use symbols in property names that are otherwise disallowed (eg.
obj['foo-bar'],arr[123]) - Have closer resemblance to the associative arrays of other languages such as PHP.
nameis a string