为什么原型函数无法读取原型属性

Why wouldn't a prototype function be able to read a prototype property?

本文关键字:原型 读取 属性 函数 为什么      更新时间:2023-09-26

我有这段代码,它返回一个未捕获的引用错误:未定义年份。

function Car(color, drivetrain) {
    this.color = color;
  this.drivetrain = drivetrain;
  this.stats = function(){
  console.log(color + " " + drivetrain);
  };
}
Car.prototype.year = 2012;
Car.prototype.funcyear = function () { console.log(year);}; //reference error
var toyota = new Car('red', 'fwd');
toyota.stats();
console.log(toyota.year);
toyota.funcyear();

为什么这不能工作,funcyear功能不应该位于原型中,所以年份应该是可访问的吗?

因为只有year会引用变量(或函数),而不是属性。
若要引用属性,必须命名对象,此属性将附加到。

Car.prototype.funcyear = function() {
    console.log(this.year);
};

注意:

function Car(color, drivetrain) {
    this.color = color;
    this.drivetrain = drivetrain;
    this.stats = function(){
        //this part is "dangerous", because color and drivetrain reference the local variables 
        //in this surrouunding function-call, NOT the properties of this instance
        //so you might change the properties, but you don't see any effect.
        console.log(color + " " + drivetrain);
    };
}