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();
__proto__
会被设置为new
执行的是的Person
的prototype
。person
与p
的new
语句之间,Person.prototype
发生了变化,所以他们自然是不同的。person
在new
的时候,Person.prototype
还不存在,所以也找不到后来定义sayAge
。==== 补充 ====
Person.prototype.sayHi =
因为此时Person.prototype
跟person.__proto__
是同一个对象。Person.prototype.sayHi =
与person.__proto__.sayHi =
的效果是一样的。Person.prototype =
会使得Person.prototype
变成与原来无关的另一个对象。