V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
yagamil
V2EX  ›  JavaScript

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

  •  
  •   yagamil · 276 天前 · 1008 次点击
    这是一个创建于 276 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    如果您想在函数里面定义 this.decorators 并且在后续的代码中添加元素,您可以在函数中先初始化 this.decorators 对象,然后再添加属性。”
    yagamil
        6
    yagamil  
    OP
       276 天前 via Android
    @echo0x000001 谢谢大佬。
    谢谢其他回复的老师。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2685 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:18 · PVG 19:18 · LAX 04:18 · JFK 07:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.