Javascript 方法没有看到对象变量
Javascript method doesn't see object variable
var Shape = function(type)
{
this.type = type;
addEventListener("resize", this.align);
}
Shape.prototype.align = function()
{
alert(this.type);
}
.
var variable = new Shape('rectangle');
当我调整大小时,我想要警告 rectangle 但它警告 undefined
您需要使用 variable.align()
,因为您正在创建一个新对象。通过这样做,我得到了你所要求的:带有 'rectangle'
.
的警报
您需要传递作用域才能在 resize
事件中使用 this
。
var Shape = function(type) {
this.type = type;
addEventListener("resize", this.align.bind(this));
}
Shape.prototype.align = function() {
alert(this.type);
}
var variable = new Shape('rectangle');
The value of this
is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called [MDN]
Function.prototype.bind()
方法创建一个新函数,调用时将其 this 关键字设置为提供的值。
var Shape = function(type) {
this.type = type;
addEventListener("resize", function() {
this.align();
}.bind(this));
//OR addEventListener("resize", this.align.bind(this));
}
Shape.prototype.align = function() {
alert(this.type);
}
var variable = new Shape('rectangle');
var Shape = function(type)
{
this.type = type;
addEventListener("resize", this.align);
}
Shape.prototype.align = function()
{
alert(this.type);
}
.
var variable = new Shape('rectangle');
当我调整大小时,我想要警告 rectangle 但它警告 undefined
您需要使用 variable.align()
,因为您正在创建一个新对象。通过这样做,我得到了你所要求的:带有 'rectangle'
.
您需要传递作用域才能在 resize
事件中使用 this
。
var Shape = function(type) {
this.type = type;
addEventListener("resize", this.align.bind(this));
}
Shape.prototype.align = function() {
alert(this.type);
}
var variable = new Shape('rectangle');
The value of
this
is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called [MDN]
Function.prototype.bind()
方法创建一个新函数,调用时将其 this 关键字设置为提供的值。
var Shape = function(type) {
this.type = type;
addEventListener("resize", function() {
this.align();
}.bind(this));
//OR addEventListener("resize", this.align.bind(this));
}
Shape.prototype.align = function() {
alert(this.type);
}
var variable = new Shape('rectangle');