2017-06-17 76 views
0

我是學習Node.js的新手。爲什麼console.log會給我定義?我希望它能打印出'Hello World!'代替。我錯在哪裏?Nodejs調用函數

謝謝!

function Greetr() { 
    this.greeting = 'Hello World!'; 
} 


Greetr.prototype.greet = function() { 
    console.log(this.greeting); 
} 

Greetr.prototype.greet(); 
+2

可能重複調用你greet功能是否有functionName調用函數之間有什麼區別.prototype.methodName()和funObject.methodName()?](https://stackoverflow.com/questions/44517936/is-there-any-difference-between-calling-function-in-functionname-prototype-metho) –

回答

1

因爲你通過你的原型訪問你的問候。在這種情況下,this不是您所期望的對象。通過記錄,你可以看到什麼是this

function Greetr() { 
 
    this.greeting = 'Hello World!'; 
 
} 
 

 
Greetr.prototype.greet = function() { 
 
    console.log(this); 
 
} 
 

 
Greetr.prototype.greet();

正如你看到的,this指的是你prototype object,它不具有名稱greeting任何財產,所以登錄undefined

得到你需要先創建一個object期望的結果,然後通過的[即object

function Greetr() { 
 
    this.greeting = 'Hello World!'; 
 
} 
 

 

 
Greetr.prototype.greet = function() { 
 
    console.log(this.greeting); 
 
} 
 

 
var greetr = new Greetr(); 
 
greetr.greet();