Skip to content

Object construction in JavaScript

Super Short History

Brendan Eich designed Mocha in 10 days, the language was officially called LiveScript, then was renamed JavaScript because of the spin-off of Java. (a marketing ploy)

JavaScript is noting like Java, but designed to syntaxly like Java.

Function Constructor

Use capital letter for function constructor: prevent missing “new” operator during construction

operator “new”

The “new” keyword is designed to make Java user feel comfortable. It is an operator in JavaScript.

  1. Create an empty object
  2. Invoke the function, point the keyword “this” to the empty object
  3. Pointing prototype to the function constructor
  4. Return the object

We can construct an object via function (function constructor) – just an regular function.

prototype extension
Build-in function constructors

Pure Prototypal Inheritance

Change the prototype along the way

Make object and create new objects by pointing prototype to this object using Object.create(), and override properties and methods.

Implement in newer browsers

Use polyfill, note the scenario of usage

ref:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill

ES6 Classes

JavaScript doesn’t have classes until ES6, even though class keyword been added, but it still an object not a definition in other programming language.

Just another syntactical way(syntactic sugar) to construct objects.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *