2016-07-11 1 views
-1
<!DOCTYPE html> 
<html> 
<head> 
<title>A generalized object declaration - Javascript</title> 
</head> 
<body> 
<script type="text/javascript"> 
function myBooks(name,author,bookType,printCost,purchaseCost){ 
    this.name = name; 
    this.author = author; 
    this.bookType =bookType; 
    this.printCost = printCost; 
    this.purchaseCost =purchaseCost; 
    var checkProfit = (function(){ 
     return this.printCost-this.purchaseCost; 

    }()); 
} 

var book1 = new myBooks('Elon Musk','Ashlee Vance','Biography',699,500); 
document.write('Profit from '+ book1.name + ' = ' + book1.checkProfit); 
</script> 
</body> 
</html> 

こんにちは、私はコンストラクタ関数を使用してオブジェクトを宣言しているJavascriptで基本コードを書いています。ここで、私のコードの20行目で、book1.checkProfitは値NaNを取得していますが、他の変数は正常に動作しています。誰でも私のコードでエラーを説明することができます。これを=希望の出力が得られないので、このコードで何が問題になっていますか?

+2

なぜあなたは使用していません: 'var checkProfit = this.printCost - this.purchaseCost'? – MHS

+0

私はすぐに呼び出された無名関数の概念を学び、適用しようとしています。そのため、この方法を好む。 –

+2

'checkProfit'は' myBooks'のローカル変数です。関数の外部からアクセスすることはできません。これをプロパティとして定義します(例: 'this.checkProfit = ...')。 – Teemu

答えて

2

使用することは、あなたのcheckProfit内でこのウィンドウ

function myBooks(name,author,bookType,printCost,purchaseCost){ 
    this.name = name; 
    this.author = author; 
    this.bookType =bookType; 
    this.printCost = printCost; 
    this.purchaseCost =purchaseCost; 
    var that = this; 
    this.checkProfit = (function(){ 
     return that .printCost-that.purchaseCost; 

    }()); 
} 

か、まあこの1つは私のために働い

function myBooks(name,author,bookType,printCost,purchaseCost){ 
    this.name = name; 
    this.author = author; 
    this.bookType =bookType; 
    this.printCost = printCost; 
    this.purchaseCost =purchaseCost; 
    var that = this; 
    this.checkProfit = (function(){ 
     return that .printCost-that.purchaseCost; 

    }.bind(this)()); 
} 
+0

これを試してみてください。それは私のために働いていない。 –

+0

this.checkProfitを使用すると、 –

+0

の外部から関数インスタンスのローカル変数にアクセスしようとしています。まだ動かない。 –

0

バインドを使用することができます。見てみましょう!

function myBooks(name,author,bookType,printCost,purchaseCost){ 
    this.name = name; 
    this.author = author; 
    this.bookType =bookType; 
    this.printCost = printCost; 
    this.purchaseCost =purchaseCost; 
    var that =this; 
    this.checkProfit = (function(){ 
     return parseInt(that.printCost)-parseInt(that.purchaseCost); 
    }.bind(this)()); 
}

関連する問題