我试图不重复问题,因为我已经看到一些关于道格拉斯克罗克福德的Javascript好的部分书的问题/答案
我理解这段代码的大部分内容
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();我遇到的问题是this.prototype [name]为什么不写成this.prototype.name; 我知道返回这允许链接,这里的语法看起来非常类似于jQuery但我仍然没有获得原型[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
最满意答案
obj.name和obj[name]之间存在差异。
这个...
obj.name = 123;...将值123分配给( "name"属性(对象)。
另一方面,这......
obj[ name ] = 123;...将值123赋给那些名称等于name变量/参数值的属性。
所以:
var name = 'foo'; obj.name = 123; obj[ name ] = 456; // And now: obj.name; // 123 obj.foo; // 456There 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更多推荐
发布评论