Skip to content

Instantly share code, notes, and snippets.

@saipraveen-a
Created September 19, 2020 13:51
Show Gist options
  • Save saipraveen-a/a09dd560662f801309ce255ffeb02f06 to your computer and use it in GitHub Desktop.
Save saipraveen-a/a09dd560662f801309ce255ffeb02f06 to your computer and use it in GitHub Desktop.
JavaScript Understanding the Weird Parts - Creating Objects using Object.create

Function Constructors were added for programmers coming from OO programming backgrounds.

Javascript also supports creating Objects using its own Prototypal Inheritance through the use of Object.create()

Objects dont create new Execution Context. Only a function invocation results in the Creation and Execution of new Execution Context.

Object.create is supported in newer browser versions. If we have to run our application in older browsers, we can instead use Polyfills (code that adds a feature that the engine may lack)

var person = {
firstName: 'Default',
lastName: 'Default',
greet: function() {
return 'Hi' + this.firstName; // using just the firstName will not work.
}
}
var john = Object.create(person); // this sets the person object as john's prototype.
console.log(john)
john.firstName = 'First Name'; // these are set on the new object created.
john.lastName = 'Last Name';
john.greet();
// Polyfill
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create accepts only 1 argument');
}
function F() {}; // dummy function which we will use for creating object using Function Constructor
F.prototype = o; // this ensures the passed in object is set as the prototype(__proto__) of the new object being created
return new F(); // function constructor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment