Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Created May 16, 2017 11:10
Show Gist options
  • Save jdmichaud/854aa21a9b3964e8d67085faad192273 to your computer and use it in GitHub Desktop.
Save jdmichaud/854aa21a9b3964e8d67085faad192273 to your computer and use it in GitHub Desktop.
Javascript Object and Prototype
> // By default, functions are applied to the window object
> function foo() { this.bar = 42; };
> foo();
> window.bar;
42
> // window properties are globals in the browser
> bar
42
> delete window.bar
> bar
undefined
> // We can apply a function to a particular object
> let o = {};
> foo.apply(o);
> bar
undefined
> o.bar;
42
> // We can ask the javascript VM to create that object for us using new
> const o2 = new foo();
> o2.bar
42
> // By default object don't have prototype
> let o = {};
> o.bar;
undefined
> o.prototype;
undefined
> // We can add prototype manually to an object
> Object.setPrototypeOf(o, { bar: 42 });
> o.prototype
{ bar: 42 }
> // If an attribute is not found on an object, the VM will look
// at the prototype (and recursively at the prototype's prototype)
> o.bar
42
> o.bar = 5;
> o.bar;
5
> o.prototype.bar;
42
> // Object created from a function, ihherits its prototype
> function foo() {};
> foo.prototype.baz = 666;
> const o2 = new foo();
> o2.baz
666
> o2.baz = 42;
> o2.baz;
42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment