为什么原型函数无法读取原型属性
Why wouldn't a prototype function be able to read a prototype property?
我有这段代码,它返回一个未捕获的引用错误:未定义年份。
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);
};
}
相关文章:
- 从桌面读取python文件时高亮显示代码
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 使用Dnamics CRM 2011中的JavaScript读取子网格的所有记录,而不考虑活动页面
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 使用“;这个“;JavaScript原型方法中的关键字
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 为什么原型函数无法读取原型属性
- 高图表热图 未捕获类型错误:无法读取未定义的属性“原型”
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 未捕获的类型错误:无法读取未定义的属性“原型”
- 如何在原型中读取json对象
- this.collection.reset引发错误-未捕获类型错误:无法读取属性'原型'的未定义
- 不能读取元素.firefox中的原型
- 扩展类不能读取未定义的属性原型
- 未捕获的类型错误:无法读取属性'原型'使用Openerp 7.0时为null
- 未捕获的类型错误:无法读取未定义的 sails.io.js 的属性“原型”
- 无法读取属性'原型'扩展类时未定义的
- 升级到量角器4后无法读取未定义的属性“原型”