请问一下这个 js 代码里面的报错问题 prototype

288 天前
 yagamil

在那边《 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 这些术语不太熟,可能问的不太明白,见谅了~

1028 次点击
所在节点    JavaScript
6 条回复
zangbianxuegu
288 天前
BasicServer.prototype.decorators 没有定义
nikoxie
288 天前
BasicServer.prototype.decorators= {
nodeServer : {
init: function(i) {
print('init node Server');
print(i);
}
}
}
echo0x000001
288 天前
prototype 指向类的原型,this 指向类的实例自身,在这个类没有实例化之前,this 是不存在的。
echo0x000001
288 天前
所以上面的 this.decorators 对于后面的原型定义没有任何影响,甚至实例化后,还会覆盖原型属性,无法直接访问到你定义的 nodeServer
jixule
288 天前
直接问 codeium 吧:
“这是因为在定义 BasicServer.prototype.decorators.nodeServer 之前,您没有初始化 BasicServer.prototype.decorators 对象。因此,在尝试添加元素到未定义的对象时会出现错误。

通过注释掉的方法,您实际上是先初始化了 BasicServer.prototype.decorators 对象,然后再给它添加了一个属性 nodeServer 。

如果您想在函数里面定义 this.decorators 并且在后续的代码中添加元素,您可以在函数中先初始化 this.decorators 对象,然后再添加属性。”
yagamil
287 天前
@echo0x000001 谢谢大佬。
谢谢其他回复的老师。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/959728

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX