我怎么做foo()?
檔案 1.js:
module.exports = class Example{
constructor(something){
this.something = something
}
functions ={
foo(){
return this.something
}
}
}
檔案2.js:
const Example = require('./file1.js')
const object = new Example("among")
console.log(object.foo())
uj5u.com熱心網友回復:
第一:您必須通過這些功能訪問這些功能,.functions因為那是它們居住的地方
其次,this不會是正確的,所以你可以
做
foo一個箭頭函式或者你可以
.bind(this)使用一個函式 - 就像bar這段代碼中的你不能
.bind在使用函式屬性簡寫時使用 - 即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())
uj5u.com熱心網友回復:
洗掉functions:
class Example{
constructor(something){
this.something = something;
}
foo(){
return this.something
}
}
const object = new Example("among")
console.log(object.foo())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471698.html
標籤:javascript 节点.js 哎呀
上一篇:僅具有類方法與模塊的類中的繼承
下一篇:可運行介面實體化
