<!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,而其他变量工作正常。任何人都可以解释我的代码中的错误。
答案 0 :(得分:2)
使用那个= this,这是在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;
}());
}
或者你可以使用bind
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)());
}
答案 1 :(得分: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)());
}