Skip to content

Commit

Permalink
Added .new function syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyObtiva authored and posva committed Jun 21, 2015
1 parent 2f758b2 commit 28e9bd0
Show file tree
Hide file tree
Showing 4 changed files with 808 additions and 351 deletions.
11 changes: 8 additions & 3 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,15 @@ var Dog = Base.extend({
// Forget about classes, javascript is a prototypal language:
typeof Dog // object

// Use new operator to create an instance
// Use the new operator to create an instance:
var dog = new Dog()
dog.bark() // 'Ruff! Ruff!'

// Alternatively you can use the legacy new() function but keep in mind that
// the new operator is faster in most browsers
var dog = Dog.new()
dog.bark() // 'Ruff! Ruff!'

// Forget about special `instanceof` operator, use JS native method instead:
Dog.prototype.isPrototypeOf(dog) // true

Expand Down Expand Up @@ -140,7 +145,7 @@ pink.cyan() // 0.0000
### Combining composition & inheritance ###

```js
var Pixel = Color.extend({
var pixel = new Pixel(11, 23, 'CC3399')
initialize: function initialize(x, y, color) {
Color.initialize.call(this, color)
this.x = x
Expand All @@ -151,7 +156,7 @@ var Pixel = Color.extend({
}
})

var pixel = new Pixel(11, 23, 'CC3399')
var pixel = Pixel.new(11, 23, 'CC3399')
pixel.toString() // 11:23@#CC3399
Pixel.prototype.isPrototypeOf(pixel) // true

Expand Down
28 changes: 28 additions & 0 deletions selfish.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,29 @@
*/
Base.prototype.initialize = function BaseInitialize() {};

/**
* Constructs an instance. An alternative maker function to using new keyword.
*
* @examples
*
* var Pet = Dog.extend({
* initialize: function initialize(options) {
* this.name = options.name;
* },
* call: function(name) {
* return this.name === name ? this.bark() : '';
* },
* name: null
* });
* var pet = Pet.new({ name: 'Benzy', breed: 'Labrador' });
* pet.call('Benzy'); // 'Ruff! Ruff!'
*/
Base.new = function() {
var instance = Object.create(Base.prototype);
Base.apply(instance, arguments)
return instance;
};

/**
* Takes any number of argument objects and returns frozen, composite object
* that inherits from `this` object and combines all of the own properties of
Expand Down Expand Up @@ -182,6 +205,11 @@
});
// Copy the prototype methods that allows us to do inheritance
constructor.extend = this.extend;
constructor.new = function() {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments)
return instance;
};

// Generate the prototype and extend it
var descriptor = Object.create(this.prototype);
Expand Down
Loading

0 comments on commit 28e9bd0

Please sign in to comment.