Function.prototype.method什么是原型[name](Function.prototype.method what is prototype[name])

编程入门 行业动态 更新时间:2024-10-27 08:27:24
Function.prototype.method什么是原型[name](Function.prototype.method what is prototype[name])

我试图不重复问题,因为我已经看到一些关于道格拉斯克罗克福德的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; // 456

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

更多推荐

本文发布于:2023-08-03 17:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393515.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原型   Function   prototype   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!