[英]Javascript object function is returning null
我正在嘗試用Javascript(Node.js)做一個非常簡單的OOP,但是有問題。 我已經嘗試了所有方法,包括搜索,但沒有找到答案。
基本上,我有以下文件Test.js:
class Test {
constructor(){
this.name = 'Hey';
this.config = 'null!';
console.log('this.config: ' + this.config);
}
config(msg){
this.config = msg;
console.log('new this.config: ' + this.config);
}
}
module.exports = Test;
(我也嘗試過這個:)
function Test()
{
this.name = 'Hey';
this.config = 'null!';
console.log('this.config: ' + this.config);
}
Test.config = function(msg) // and Test.prototype.config
{
this.config = msg;
console.log('new this.config: ' + this.config);
}
module.exports = Test;
我還有另一個文件app.js:
var TestModule = require('./Test.js');
var Test = new TestModule();
var test = Test.config('hi');
我嘗試過的其他方式:
var TestModule = require('./Test.js');
var Test = new TestModule().config('hi');
而且也沒有用。
我已經嘗試了許多不同的方法,但是無論如何,當我嘗試在同一實例中運行config函數時,對象變為null ...有人知道為什么會發生這種情況嗎? 也許我缺少真正明顯的東西。
您正在將var Test
分配為config
函數的return
值。
var test = Test.config('hi!');
由於config
不返回任何內容,因此將導致test
為空。
您應該使config
方法返回某些內容(這將是“方法鏈”設計模式的一種形式),或者干脆不將config
調用的結果分配給變量。
例如,您可以簡單地執行以下操作:
var test = new TestModule();
test.config('hi!');
// the 'test' variable still contains a reference to your test module
你的第一段是正確的
class Test {
constructor() {
this.name = 'Hey';
this.config = 'null!';
console.log('this.config: ' + this.config);
}
config(msg) {
this.config = msg;
console.log('new this.config: ' + this.config);
}
}
module.exports = Test;
config
是實例方法,不是類方法或靜態方法。
您需要在測試實例上調用config()
。 喜歡
var Test = require('./Test.js');
var testObj = new Test();
現在testObj
是實例,您可以在此對象上調用config()
方法。
test.config('Hi');
它會打印/記錄一條消息,但它不會返回任何東西,但會返回undefined
因為您沒有從該方法返回任何信息。
我希望這可以解釋問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.