这段代码有什么问题,因为我没有得到所需的输出?

时间:2016-07-11 07:46:11

标签: javascript html

<!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 个答案:

答案 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)());
}