ES6 Class 'this' 用于非 class 方法
ES6 Class 'this' to be used in non class method
let dispNameExt = () => {
console.log(this.name);
};
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
dispNameExt();
}
}
class 之外的外部方法访问 'this of the class' 中的这段代码如何工作?
let dispNameExt = (model) => {
console.log(model.name);
};
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
dispNameExt(this);
}
}
由于您对 dispNameExt
使用箭头函数,我相信唯一的方法是将 this
值作为参数传递给函数。
let dispNameExt = (thisValue) => {
console.log(thisValue.name);
};
但如果您将其更改为使用普通 function
,则有多种方法可以在函数内指定 this
的值。
function dispNameExt() {
console.log(this.name);
}
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
// Using .apply()
dispNameExt.apply(this);
// Using .call()
dispNameExt.call(this);
// Using .bind()
dispNameExt.bind(this)();
}
}
应该重构为static prop。当然可以在不实例化 class.
的情况下访问
由于 name
属性 名称 is reserved,必须选择另一个 属性 名称。
let dispNameExt = () => {
console.log(MyName.title);
};
class MyName {
static get title() {
return 'lsr';
}
dispName() {
dispNameExt();
}
}
let dispNameExt = () => {
console.log(this.name);
};
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
dispNameExt();
}
}
class 之外的外部方法访问 'this of the class' 中的这段代码如何工作?
let dispNameExt = (model) => {
console.log(model.name);
};
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
dispNameExt(this);
}
}
由于您对 dispNameExt
使用箭头函数,我相信唯一的方法是将 this
值作为参数传递给函数。
let dispNameExt = (thisValue) => {
console.log(thisValue.name);
};
但如果您将其更改为使用普通 function
,则有多种方法可以在函数内指定 this
的值。
function dispNameExt() {
console.log(this.name);
}
class MyName {
constructor() {
this.name = 'lsr';
}
dispName() {
// Using .apply()
dispNameExt.apply(this);
// Using .call()
dispNameExt.call(this);
// Using .bind()
dispNameExt.bind(this)();
}
}
应该重构为static prop。当然可以在不实例化 class.
的情况下访问由于 name
属性 名称 is reserved,必须选择另一个 属性 名称。
let dispNameExt = () => {
console.log(MyName.title);
};
class MyName {
static get title() {
return 'lsr';
}
dispName() {
dispNameExt();
}
}