-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>

Hi, I have written a basic code in Javascript in which I am declaring an object using constructor function. Here, in 20th line of my code, book1.checkProfit is getting value NaN while other variables are working fine. Can anyone explain the error in my code.

2 Answers2

2

Use that = this , this inside your checkProfit is window

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;

    }());
}

OR you can use 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)());
}
Piyush.kapoor
  • 6,041
  • 1
  • 17
  • 18
0

Well this one worked out for me. Have a look!

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)());
}
Deepak Singh
  • 440
  • 1
  • 3
  • 16