如何在 javascript class 中的对象中使用变量
how to use a variable in in an object in a javascript class
如何使 foo()
工作?
file1.js:
module.exports = class Example{
constructor(something){
this.something = something
}
functions ={
foo(){
return this.something
}
}
}
file2.js:
const Example = require('./file1.js')
const object = new Example("among")
console.log(object.foo())
移除functions
:
class Example{
constructor(something){
this.something = something;
}
foo(){
return this.something
}
}
const object = new Example("among")
console.log(object.foo())
首先:您必须通过 .functions
访问这些功能,因为那是它们所在的地方
其次,this
不会正确,所以你可以
使foo
成为箭头函数
或者您可以 .bind(this)
函数 - 就像此代码中的 bar
你不能在使用函数 属性 时使用 .bind
shorthand 虽然 - 即 foo() { return this.something }.bind(this)
- 但你可以将它绑定在 constructor
查看所有三个解决方案的代码 - 以及为什么需要绑定非箭头函数
class Example{
constructor(something){
this.something = something;
// bat needs to be bound here
this.functions.bat = this.functions.bat.bind(this);
}
functions ={
// "this" will be correct here
foo: () => this.something,
// bar needs to be bound to "this"
bar: function() { return this.something }.bind(this),
// you can't bind a shorthand property function though
bat() { return this.something },
// this is what happens with no bind
baz() { return this.something },
}
}
const object = new Example("among")
console.log('foo', object.functions.foo())
console.log('bar', object.functions.bar())
console.log('bat', object.functions.bat())
console.log('baz', object.functions.baz())
如何使 foo()
工作?
file1.js:
module.exports = class Example{
constructor(something){
this.something = something
}
functions ={
foo(){
return this.something
}
}
}
file2.js:
const Example = require('./file1.js')
const object = new Example("among")
console.log(object.foo())
移除functions
:
class Example{
constructor(something){
this.something = something;
}
foo(){
return this.something
}
}
const object = new Example("among")
console.log(object.foo())
首先:您必须通过 .functions
访问这些功能,因为那是它们所在的地方
其次,this
不会正确,所以你可以
使
foo
成为箭头函数或者您可以
.bind(this)
函数 - 就像此代码中的bar
你不能在使用函数 属性 时使用
.bind
shorthand 虽然 - 即foo() { return this.something }.bind(this)
- 但你可以将它绑定在constructor
查看所有三个解决方案的代码 - 以及为什么需要绑定非箭头函数
class Example{
constructor(something){
this.something = something;
// bat needs to be bound here
this.functions.bat = this.functions.bat.bind(this);
}
functions ={
// "this" will be correct here
foo: () => this.something,
// bar needs to be bound to "this"
bar: function() { return this.something }.bind(this),
// you can't bind a shorthand property function though
bat() { return this.something },
// this is what happens with no bind
baz() { return this.something },
}
}
const object = new Example("among")
console.log('foo', object.functions.foo())
console.log('bar', object.functions.bar())
console.log('bat', object.functions.bat())
console.log('baz', object.functions.baz())