Created
October 4, 2013 16:44
-
-
Save keeganwatkins/6828935 to your computer and use it in GitHub Desktop.
Defining a constructor and it's prototype methods all in a single call.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a fairly common pattern. First, define a constructor... | |
var Person = function(firstName, lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
}; | |
// ...then define some methods by mixing into the prototype | |
$.extend(Person.prototype, { | |
sayHello: function() { | |
console.log('Hello, I\'m ' + this.getFullName()); | |
}, | |
getFullName: function() { | |
return this.firstName + ' ' + this.lastName; | |
} | |
}); | |
// Example use: | |
var person = new Person('Keegan', 'Watkins'); | |
person.sayHello(); // logs "Hello, I'm Keegan Watkins" | |
// As a shorthand though, we can define the constructor AND | |
// the prototype methods in a single call, like this: | |
var Person2 = $.extend(function(firstName, lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
}.prototype, { | |
sayHello: function() { | |
console.log('Hello, I\'m ' + this.getFullName()); | |
}, | |
getFullName: function() { | |
return this.firstName + ' ' + this.lastName; | |
} | |
}).constructor; | |
// The way this works is that the first parameter to `$.extend` is the prototype of our constructor, | |
// and the second parameter is the object literal of method definitions. Because `$.extend` returns | |
// the target, we can't just assign the `Person2` variable to the return value of `$.extend`, but we can | |
// access the `constructor` of the returned prototype to set the `Person2` variable back to the constructor | |
// we started with. | |
// Example use: | |
var person2 = new Person2('Keegan', 'Watkins'); | |
person2.sayHello(); // Logs "Hello, I'm Keegan Watkins" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment