Skip to content

Instantly share code, notes, and snippets.

@g-k
Last active December 15, 2015 20:09
Show Gist options
  • Save g-k/5316218 to your computer and use it in GitHub Desktop.
Save g-k/5316218 to your computer and use it in GitHub Desktop.
JS new this
var A = function () {
  console.log('calling A with this:', this);
  this.name = 'A';
  return new this;
};
var B = function () {
  console.log('calling B with this:', this);
  this.name = 'B';
};

// call it directly?
A()
> calling A with this: Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
> TypeError: object is not a function

// call it as a constructor?
new A
> calling A with this: A {}
> TypeError: object is not a function

// this can be a function and functions are objects  
A.call(B)
> calling A with this: function () {
console.log('calling B with this:', this);
this.name = 'B';
}
> calling B with this: B {}
B {name: "B"} // returns an instance of b

// equivalently set a callable host object
B.newB = A;
B.newB()

In the wild: JS.Class classmethods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment