修改prototype前后定义的对象?

function Person() {
}
var person = new Person();
Person.prototype = {
  constructor: Person, 
    sayAge: function() {
        console.info("i'm ", this.age, " years old.");
    }
}
var p = new Person();

1.为什么用p.sayAge()正常,person.sayAge()会报错sayAge不是一个函数?
2.console.info(p.__proto__ === person.__proto__);为什么是false
3.关于箭头函数,如果我把sayAge改成了箭头函数,为什么this.age变成了undefined.

请教大家,谢谢了

======================2. 补充=======================

function Person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;

    // 写法一
    this.saySex = function() {
        console.info("i'm a " + this.sex);
    }
}
var person = new Person("person", 12, "male");
Person.prototype.sayHi = function() {
    console.info("Hi, i'm ", this.name);
}

Person.prototype = {
  constructor: Person, 
    sayAge: function() {
        console.info("i'm ", this.age, " years old.");
    }
}
var p = new Person();
阅读 1.2k
1 个回答
  1. 见2
  2. __proto__ 会被设置为 new 执行的是的 Personprototypepersonpnew 语句之间,Person.prototype 发生了变化,所以他们自然是不同的。personnew 的时候,Person.prototype 还不存在,所以也找不到后来定义 sayAge
  3. 箭头函数的 this 是定义是决定的,不是调用时决定的。

==== 补充 ====

Person.prototype.sayHi = 因为此时 Person.prototypeperson.__proto__ 是同一个对象。Person.prototype.sayHi = person.__proto__.sayHi = 的效果是一样的。

Person.prototype = 会使得 Person.prototype 变成与原来无关的另一个对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题