1

I'm using object.create to create an object, based on a prototype I created.

This is the prototype

var employeePrototype = {
            calulateTax: function() {
                console.log(salary * taxRate);
            }
        };

This is the object I created.

var jack = Object.create(employeePrototype);
        jack.salary = 25000;
        jack.taxRate = .40;
        jack.calulateTax();

When I call jack.calculateTax, I get the following error

index.html:14 Uncaught ReferenceError: salary is not defined at Object.calulateTax

0

2 Answers 2

2

You have to use this to use the salary and taxRate of the instance

var employeePrototype = {
  calulateTax: function() {
    console.log(this.salary * this.taxRate);
  }
};

var jack = Object.create(employeePrototype);
jack.salary = 25000;
jack.taxRate = .40;
jack.calulateTax();

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using Object.create(), it's a lot more orthodox to use a class. Here's how you'd accomplish it using one:

class Employee {
  salary = 25000;
  taxRate = .40;

  calulateTax () {
    console.log(this.salary * this.taxRate);
  }
}

const jack = new Employee();

jack.calulateTax();

The class fields are part of TC39/proposal-class-fields, which is in stage 3, but is already part of Chrome, Firefox, and Node.js, or can be transpiled using Babel.

For ES2015 support, you can simply move the initialization into the constructor:

class Employee {
  constructor () {
    this.salary = 25000;
    this.taxRate = .40;
  }

  calulateTax () {
    console.log(this.salary * this.taxRate);
  }
}

const jack = new Employee();

jack.calulateTax();

1 Comment

Thank you, and I appreciate it. I'm just going through a course atm, so this is how they do it. ES6 and stuff is coming up soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.