V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yantianqi
V2EX  ›  程序员

问个 js 动态原型问题

  •  
  •   yantianqi · 2016-11-21 22:51:32 +08:00 · 1446 次点击
    这是一个创建于 2729 天前的主题,其中的信息可能已经有所发展或是发生改变。

    方法 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 条回复    2016-11-22 07:44:47 +08:00
    xingo
        1
    xingo  
       2016-11-21 23:02:11 +08:00
    你在构造时把 Person 原型都替换掉了,那 person1 的原型当然就不是 Person 的实例啦

    https://ooo.0o0.ooo/2016/11/21/58330c6c69584.png
    aleen42
        2
    aleen42  
       2016-11-21 23:07:07 +08:00
    你这样的话, prototype 的确被替换掉而只剩下 sayName 方法,那么 this.name 应该是 undefined
    xingo
        3
    xingo  
       2016-11-21 23:25:27 +08:00
    @aleen42 不会, sayName 是直接报错, person1 在 new 时进入 constructor 之前,其实例已经创建,之后才把构造函数中的 this 替换成实例进行添加方法和属性,现在是他把 Person 的 prototype 给替换了,那么 person1 的__proto__其实已经不是当时的 Person.prototype ,自然没有 sayName 这个方法
    aleen42
        4
    aleen42  
       2016-11-22 07:44:47 +08:00
    @xingo 哦哦 明白
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3788 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:42 · PVG 18:42 · LAX 03:42 · JFK 06:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.