在那边《 Javascript 编程精髓》里面的例子。
代码: https://output.jsbin.com/zupezayihi
var print = console.log; function BasicServer() { this.decorator_list = [] this.decorators = {} } BasicServer.prototype.init = function() { for (var i = 0; i < this.decorator_list.length; i++) { var func = this.decorator_list[i] this.decorators[func].init(i) } } BasicServer.prototype.decorated = function(i) { this.decorator_list.push(i) } //BasicServer.prototype.decorators = {} BasicServer.prototype.decorators.nodeServer = { init: function(i) { print('init node Server'); print(i); } }
为什么我在函数里面定义的变量
this.decorators = {}
在 BasicServer.prototype.decorators.nodeServer 添加元素的时候会提示 nodeServer undefine ?
用注释掉的方法就可以, BasicServer.prototype.decorators = {}
对 prototype 这些术语不太熟,可能问的不太明白,见谅了~
![]() | 1 zangbianxuegu 2023-07-26 09:08:53 +08:00 BasicServer.prototype.decorators 没有定义 |
2 nikoxie 2023-07-26 09:27:29 +08:00 BasicServer.prototype.decorators= { nodeServer : { init: function(i) { print('init node Server'); print(i); } } } |
![]() | 3 echo0x000001 2023-07-26 09:48:51 +08:00 ![]() prototype 指向类的原型,this 指向类的实例自身,在这个类没有实例化之前,this 是不存在的。 |
![]() | 4 echo0x000001 2023-07-26 09:50:18 +08:00 ![]() 所以上面的 this.decorators 对于后面的原型定义没有任何影响,甚至实例化后,还会覆盖原型属性,无法直接访问到你定义的 nodeServer |
5 jixule 2023-07-26 10:27:17 +08:00 直接问 codeium 吧: “这是因为在定义 BasicServer.prototype.decorators.nodeServer 之前,您没有初始化 BasicServer.prototype.decorators 对象。因此,在尝试添加元素到未定义的对象时会出现错误。 通过注释掉的方法,您实际上是先初始化了 BasicServer.prototype.decorators 对象,然后再给它添加了一个属性 nodeServer 。 如果您想在函数里面定义 this.decorators 并且在后续的代码中添加元素,您可以在函数中先初始化 this.decorators 对象,然后再添加属性。” |
6 yagamil OP @echo0x000001 谢谢大佬。 谢谢其他回复的老师。 |