Back to Home

Javascript Cheatsheet for Job Interview

Object literal and Object Constructor

Don't forget, javascript can ack like Object Oriented Language. There are two ways to construct object and class like object.

var sarah = { name: "Sarah Kwak" postcode: "94070" }; var Person = function(name, postcode) { this.name = name; this.postcode = postcode; }; sarah = new Person("Sarah Kwak", "94070") ☕ Lets adding a function to sarah Person.prototype.sayThat = function() { console.log("I am an awesome developer!") }; sarah.sayThat(); =>I am an awesome developer! ryan = new Person("Ryan", "124232"); ryan.sayThat(); =>I am an awesome developer!

Variable Scope

function Person(name) { this.name = first; var bankBalance = 7500; }; ☕bankBalance is the example of private method in javascript

Although we cannot directly access private variable - bankBalance from outside the class, there is a way to get around this. We can define a public method that returns the value of a private variable.

this.getBalance = function() { return bankBalance; }; ☕This function must be defined inside of the class so that it can access the private variable

This is how to call the function

var john = new Person('John'); console.log(john.bankBalance); => Undefined ☕Make sure define new variable and assign the value var myBalance = john.getBalance() console.log(myBalance); =>7500

There is also private method. They ack like private variables and we can access via public method inside of the class.

function Person(name) { this.name var bankBalance = 7500; var returnBalance = function() { return bankBalance; };

This is how to access the private method

this.askTeller = function() { return returnBalance; }; ☕Notice there is no () after returnBalance We don't want the result, we need the method
sarah = new Person("Sarah") var final_balance = sarah.askTeller(); console.log(final_balance);=> [Function] console.log(final_balance()) => 7500