• 请不要在回答技术问题时复制粘贴 AI 生成的内容
yantianqi
V2EX  ›  程序员

问个 js 动态原型问题

  •  
  •   yantianqi · Nov 21, 2016 · 1868 views
    This topic created in 3462 days ago, the information mentioned may be changed or developed.

    方法 1 正常,方法二没有声明 sayName 动态模型不能用字面量是吗?

    //方式一
    function Person(name){
        this.name = name;
    
        if(typeof this.sayName != "function") {
            Person.prototype.sayName = function() {
                alert(this.name);
            }
        }
    }
    
    var person1 = new Person("xiaoming");
    person1.sayName();
    
    //方式二
    function Person(name){
        this.name = name;
    
            if(typeof this.sayName != "function") {
                Person.prototype={    //这里不能用字面量是吗?
                    sayName:function() {
                        alert(this.name);
                }
            }
        }
    }
    
    var person1 = new Person("xiaoming");
    person1.sayName();
    
    4 replies    2016-11-22 07:44:47 +08:00
    xingo
        1
    xingo  
       Nov 21, 2016
    你在构造时把 Person 原型都替换掉了,那 person1 的原型当然就不是 Person 的实例啦

    https://ooo.0o0.ooo/2016/11/21/58330c6c69584.png
    aleen42
        2
    aleen42  
       Nov 21, 2016
    你这样的话, prototype 的确被替换掉而只剩下 sayName 方法,那么 this.name 应该是 undefined
    xingo
        3
    xingo  
       Nov 21, 2016
    @aleen42 不会, sayName 是直接报错, person1 在 new 时进入 constructor 之前,其实例已经创建,之后才把构造函数中的 this 替换成实例进行添加方法和属性,现在是他把 Person 的 prototype 给替换了,那么 person1 的__proto__其实已经不是当时的 Person.prototype ,自然没有 sayName 这个方法
    aleen42
        4
    aleen42  
       Nov 22, 2016
    @xingo 哦哦 明白
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2986 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:33 · PVG 17:33 · LAX 02:33 · JFK 05:33
    ♥ Do have faith in what you're doing.