What is the difference between these three module pattern implementations in JavaScript? - javascript

I've seen the following three code blocks as examples of the JavaScript module pattern. What are the differences, and why would I choose one pattern over the other?
Pattern 1
function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;
this.fullName = function () {
return firstName + ' ' + lastName;
};
this.changeFirstName = function (name) {
firstName = name;
};
};
var jordan = new Person('Jordan', 'Parmer');
Pattern 2
function person (firstName, lastName) {
return {
fullName: function () {
return firstName + ' ' + lastName;
},
changeFirstName: function (name) {
firstName = name;
}
};
};
var jordan = person('Jordan', 'Parmer');
Pattern 3
var person_factory = (function () {
var firstName = '';
var lastName = '';
var module = function() {
return {
set_firstName: function (name) {
firstName = name;
},
set_lastName: function (name) {
lastName = name;
},
fullName: function () {
return firstName + ' ' + lastName;
}
};
};
return module;
})();
var jordan = person_factory();
From what I can tell, the JavaScript community generally seems to side with pattern 3 being the best. How is it any different from the first two? It seems to me all three patterns can be used to encapsulate variables and functions.
NOTE: This post doesn't actually answer the question, and I don't consider it a duplicate.

I don't consider them module patterns but more object instantiation patterns. Personally I wouldn't recommend any of your examples. Mainly because I think reassigning function arguments for anything else but method overloading is not good. Lets circle back and look at the two ways you can create Objects in JavaScript:
Protoypes and the new operator
This is the most common way to create Objects in JavaScript. It closely relates to Pattern 1 but attaches the function to the object prototype instead of creating a new one every time:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
Person.prototype.changeFirstName = function (name) {
this.firstName = name;
};
var jordan = new Person('Jordan', 'Parmer');
jordan.changeFirstName('John');
Object.create and factory function
ECMAScript 5 introduced Object.create which allows a different way of instantiating Objects. Instead of using the new operator you use Object.create(obj) to set the Prototype.
var Person = {
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
}
var jordan = Object.create(Person);
jordan.firstName = 'Jordan';
jordan.lastName = 'Parmer';
jordan.changeFirstName('John');
As you can see, you will have to assign your properties manually. This is why it makes sense to create a factory function that does the initial property assignment for you:
function createPerson(firstName, lastName) {
var instance = Object.create(Person);
instance.firstName = firstName;
instance.lastName = lastName;
return instance;
}
var jordan = createPerson('Jordan', 'Parmer');
As always with things like this I have to refer to Understanding JavaScript OOP which is one of the best articles on JavaScript object oriented programming.
I also want to point out my own little library called UberProto that I created after researching inheritance mechanisms in JavaScript. It provides the Object.create semantics as a more convenient wrapper:
var Person = Proto.extend({
init : function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
});
var jordan = Person.create('Jordan', 'Parmer');
In the end it is not really about what "the community" seems to favour but more about understanding what the language provides to achieve a certain task (in your case creating new obejcts). From there you can decide a lot better which way you prefer.
Module patterns
It seems as if there is some confusion with module patterns and object creation. Even if it looks similar, it has different responsibilities. Since JavaScript only has function scope modules are used to encapsulate functionality (and not accidentally create global variables or name clashes etc.). The most common way is to wrap your functionality in a self-executing function:
(function(window, undefined) {
})(this);
Since it is just a function you might as well return something (your API) in the end
var Person = (function(window, undefined) {
var MyPerson = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
MyPerson.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
MyPerson.prototype.changeFirstName = function (name) {
this.firstName = name;
};
return MyPerson;
})(this);
That's pretty much modules in JS are. They introduce a wrapping function (which is equivalent to a new scope in JavaScript) and (optionally) return an object which is the modules API.

First, as #Daff already mentioned, these are not all module patterns. Let's look at the differences:
Pattern 1 vs Pattern 2
You might omit the useless lines
var firstName = firstName;
var lastName = lastName;
from pattern 1. Function arguments are already local-scoped variables, as you can see in your pattern-2-code.
Obviously, the functions are very similar. Both create a closure over those two local variables, to which only the (exposed) fullName and the changeFirstName functions have access to. The difference is what happens on instantiation.
In pattern 2, you just return an object (literal), which inherits from Object.prototype.
In pattern 1, you use the new keyword with a function that is called a "constructor" (and also properly capitalized). This will create an object that inherits from Person.prototype, where you could place other methods or default properties which all instances will share.
There are other variations of constructor patterns. They might favor [public] properties on the objects, and put all methods on the prototype - you can mix such. See this answer for how emulating class-based inheritance works.
When to use what? The prototype pattern is usually preferred, especially if you might want to extend the functionality of all Person instances - maybe not even from the same module. Of course there are use cases of pattern 1, too, especially for singletons that don't need inheritance.
Pattern 3
…is now actually the module pattern, using a closure for creating static, private variables. What you export from the closure is actually irrelevant, it could be any fabric/constructor/object literal - still being a "module pattern".
Of course the closure in your pattern 2 could be considered to use a "module pattern", but it's purpose is creating an instance so I'd not use this term. Better examples would be the Revealing Prototype Pattern or anything that extends already existing object, using the Module Pattern's closure - focusing on code modularization.
In your case the module exports a constructor function that returns an object to access the static variables. Playing with it, you could do
var jordan = person_factory();
jordan.set_firstname("Jordan");
var pete = person_factory();
pete.set_firstname("Pete");
var guyFawkes = person_factory();
guyFawkes.set_lastname("Fawkes");
console.log(jordan.fullname()); // "Pete Fawkes"
Not sure if this was expected. If so, the extra constructor to get the accessor functions seems a bit useless to me.

"Which is best?" isn't really a valid question, here.
They all do different things, come with different trade-offs, and offer different benefits.
The use of one or the other or all three (or none) comes down to how you choose to engineer your programs.
Pattern #1 is JS' traditional take on "classes".
It allows for prototyping, which should really not be confused with inheritance in C-like languages.
Prototyping is more like public static properties/methods in other languages.
Prototyped methods also have NO ACCESS TO INSTANCE VARIABLES (ie: variables which aren't attached to this).
var MyClass = function (args) { this.thing = args; };
MyClass.prototype.static_public_property = "that";
MyClass.prototype.static_public_method = function () { console.log(this.thing); };
var myInstance = new MyClass("bob");
myInstance.static_public_method();
Pattern #2 creates a single instance of a single object, with no implicit inheritance.
var MyConstructor = function (args) {
var private_property = 123,
private_method = function () { return private_property; },
public_interface = {
public_method : function () { return private_method(); },
public_property : 456
};
return public_interface;
};
var myInstance = MyConstructor(789);
No inheritance, and every instance gets a NEW COPY of each function/variable.
This is quite doable, if you're dealing with objects which aren't going to have hundreds of thousands of instances per page.
Pattern #3 is like Pattern #2, except that you're building a Constructor and can include the equivalent of private static methods (you must pass in arguments, 100% of the time, and you must collect return statements, if the function is intended to return a value, rather than directly-modifying an object or an array, as these props/methods have no access to the instance-level data/functionality, despite the fact that the instance-constructor has access to all of the "static" functionality).
The practical benefit here is a lower memory-footprint, as each instance has a reference to these functions, rather than their own copy of them.
var PrivateStaticConstructor = function (private_static_args) {
var private_static_props = private_static_args,
private_static_method = function (args) { return doStuff(args); },
constructor_function = function (private_args) {
var private_props = private_args,
private_method = function (args) { return private_static_method(args); },
public_prop = 123,
public_method = function (args) { return private_method(args); },
public_interface = {
public_prop : public_prop,
public_method : public_method
};
return public_interface;
};
return constructor_function;
};
var InstanceConstructor = PrivateStaticConstructor(123),
myInstance = InstanceConstructor(456);
These are all doing very different things.

Related

How to properly return values when using 'this' in an 'constructor' and the prototype methods of the object?

For live code sample checkout my: Codepen
Question: How can I make sure that p1.prototype.setFirst() & p1.prototype.fullName() return the proper values while still using this?
var Person = function(){
this.firstName = "Penelope";
this.lastName = "Barrymore";
}
Person.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
}
Person.prototype.setFirst = function () {
return this.firstName = "mark"
}
var p1 = new Person();
p1.prototype.setFirst()
console.log(p1.prototype.fullName());
If you really have to call via the prototype like that, you can do:
Person.prototype.setFirst.call(p1);
...and:
Person.prototype.fullName.call(p1);
call and apply are the easiest ways to change this.
If you want reference to a version of a function where this is bound to it, use bind:
var myFullName = Person.prototype.fullName.bind(p1);
myFullName(); // this will be p1
...but of course, this is the natural thing to do:
p1.fullName()
And if you want to get the prototype through the object, you can use:
p1.__proto__
...or:
p1.constructor.prototype

How can I make inheritance without third object shim?

I try to understand OOP in JavaScript.
I want to create object Person and Worker. Worker inherits Person. I wrote code:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.grow = function () {
this.age++;
console.log('Person grows, new age ' + this.age);
};
function Worker(name, age, position) {
// How to call parrent constructor Person?
this.position = position;
}
Worker.prototype = Person.prototype;
Worker.constructor = Worker.prototype.constructor;
Worker.prototype.promote = function () {
console.log('Worker ' + this.name + ' became Senior ' + this.position);
};
Worker.prototype.grow = function () {
this.promote();
// How to call parrent method grow?
};
var workerObj = new Worker('Ben', 39, 'engineer');
workerObj.grow();
But in JS variable assignment works by reference and expression Worker.prototype = Person.prototype; doesn't get result and method grow in Worker overrides method grow in Person and I will not be able to get access to parent method.
I know that I need to use third object. But is there way to inherit without third object?
Setting the functions' .prototype properties to the same object essentially makes them the same class, as you've noticed. What you really need, is for Person.prototype to be an object that inherits from Worker.prototype. But you need to do this without calling the Person constructor, since that leave some side effects back in the prototype chain (they aren't significant in the case you mention, but they could be significant in other cases). So Worker.prototype = new Person(); isn't an ideal solution for you.
Object.create() works for this. Among other things, this function can be used to create an object that inherits from another, without calling any constructors. For the situation you're talking about, it would look like this:
Worker.prototype = Object.create(Person.prototype);
Worker.prototype.constructor = Worker;
Object.create doesn't work in older versions of IE, and a total polyfill isn't available due to engine limitations. But there are polyfills for Object.create which work well enough to enable this kind of subclassing, so browser support need not be an issue.
I typically wrap this up in a function, so that once I've defined my subclass and superclass, I can express the relation without much extra rigamarole. You could do that like this:
Object.subclass = function (sub, sup) {
sub.prototype = Object.create(sup.prototype);
sub.prototype.constructor = sub;
}
Object.subclass(Worker, Person); // "class Worker extends Person"
I make inheritance in javascript like this :
var c_Parent = function () {
};
var c_Child = function () {
c_Parent .call(this);
};
c_Child.prototype = new c_Parent();
c_Child.prototype.constructor = c_Child;
So in you case :
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.grow = function () {
this.age++;
console.log('Person grows, new age ' + this.age);
};
function Worker(name, age, position) {
this.position = position;
Person.call(this, name, age);
}
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;
Worker.prototype.promote = function () {
console.log('Worker ' + this.name + ' became Senior ' + this.position);
};
Worker.prototype.grow = function () {
this.promote();
Person.prototype.grow.call(this);
};
var workerObj = new Worker('Ben', 39, 'engineer');
workerObj.grow();

Setting properties of JavaScript objects created with Object.create()

Let's say there's a simple object created with the following JavaScript
Builder = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Builder.prototype.build = function () {
return 'building....';
};
var b2 = new Builder('firstName', 'lastName');
I've been reading up on some of Douglas Crockford's work and he says that it's 'better'
to create objects like the following:
var builder = {
build: function () {
return 'building...';
}, firstName: 'firstName'
, lastName: 'lastName'
};
var b1 = Object.create(builder);
The Object.create() way is 'better' (and I would be curious to hear from an expert as to why), but I don't see how we could easily pass parameters to the second version for the values of 'firstNameand 'lastName. I'm much more familiar with C family syntax languages than JavaScript, but it seems to me that the constructor method of object creation is 'better'. Why am I wrong? (Let's say for an enterprise-level environment)
For Crockford's way, you would do the following:
var build = function(firstName, lastName) {
// do private stuff here.. but this closure will still be accessible to the returned object
return {
firstName:firstName,
lastName:lastName
}
}
var b = build('john', 'smith')
It's just as clean/powerfull as the OO way
Crockford's argument was that OO doesn't mix well with protypical inheritance. He felt as though many of the OO constructs were added to the language and should have been thought out more clearly before doing so. In my own code, I always try to follow his sound advice as he comes from the front lines :)
You can pass initial values for firstName and lastName in the second argument to Object.create():
var builder = {
getFullName : function() {
return this.firstName + " " + this.lastName;
}
};
var b1 = Object.create(builder, {
firstName : { writable:true, configurable:true, value: "Joe" },
lastName : { writable:true, configurable:true, value: "Shmoe" }
}
);
b1.getFullName() //prints out: Joe Shmoe
Its very verbose, but you can create your own wrapper.
More details/examples here.

In javascript, Is there a perfect way to define class

I am looking for a perfect way to define class. "perfect" here means:`
create instances will not create copies of methods.
public function could easily(not to much hassle) access private variable
For example, way 1:
function Foo1() {
var private1;
this.publicMethod1 = function() {//create instance will create copy of this function}
}
will not meet rule No.1 above.
Another example, way 2:
function Foo2() {
var private2;
}
Foo2.prototype.Method2 = function() {//cannot access private2}
will not meet rule No.2 above.
So is it possible to meet both rules? Thanks.
In JavaScript it's more about conventions. Private properties or methods are defined with a underscore first like _private. With a few helpers you can make classes easily. I find this setup easy enough, all you need is a helper inherits to extend classes, and instead of using multiple arguments you pass in an object props and simply call "super" on the inherited classes with arguments. For example, using a module pattern:
Function.prototype.inherits = function(parent) {
this.prototype = Object.create(parent.prototype);
};
var Person = (function PersonClass() {
function Person(props) {
this.name = props.name || 'unnamed';
this.age = props.age || 0;
}
Person.prototype = {
say: function() {
return 'My name is '+ this.name +'. I am '+ this.age +' years old.';
}
};
return Person;
}());
var Student = (function StudentClass(_super) {
Student.inherits(_super);
function Student(props) {
_super.apply(this, arguments);
this.grade = props.grade || 'untested';
}
Student.prototype.say = function() {
return 'My grade is '+ this.grade +'.';
};
return Student;
}(Person));
var john = new Student({
name: 'John',
age: 25,
grade: 'A+'
});
console.log(JSON.stringify(john)); //=> {"name":"John","age":25,"grade":"A+"}
console.log(john.say()); //=> "My grade is A+"
About the private variable "issue" just stick to convention for instance properties and use closures when needed for everything else private.
function Foo3() {
this.private = {};
}
Foo3.prototype.set_x = function (x) {
this.private.x = x;
};
To make a long story short: no, it is not. You cannot extend the prototype with methods that could access private variables. At least if these private variables are made private via a closure.
Though, it is a convention in javascript that you mark your private fields with an underscore, for example _myPrivateField. These would be still public, but i have seen this solution being used in many libraries and i also prefer that style to meet your first rule.
A basic example is below:
Foo = function(id)
{
// private instances.
var _id;
var _self = this;
// constructor
_id = id;
// private method
function _get()
{
return _id;
};
// public function
_self.set = function(id)
{
_id = id;
};
_self.get = function()
{
return _get();
};
};
var bar = Foo(100);
console.log( bar.get() );
bar.set(1000);
console.log( bar.get() );
I would recommend you use prototype.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why would it be done in that way?
I would like to avoid using third-party libraries - at least at first.
Looking for other answers, I found the article Object-Oriented Programming with JavaScript, Part I: Inheritance - Doc JavaScript that discusses object-oriented programming in JavaScript. Is there a better way to do inheritance?
Here's the way to do it without using any external libraries:
// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
};
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a prototype-based inheritance scheme.
In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least Prototype and jQuery.
Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.
As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.
The best way to define a class in JavaScript is to not define a class.
Seriously.
There are several different flavors of object-orientation, some of them are:
class-based OO (first introduced by Smalltalk)
prototype-based OO (first introduced by Self)
multimethod-based OO (first introduced by CommonLoops, I think)
predicate-based OO (no idea)
And probably others I don't know about.
JavaScript implements prototype-based OO. In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template) and methods live directly in objects instead of in classes. Inheritance is done via delegation: if an object doesn't have a method or property, it is looked up on its prototype(s) (i.e. the object it was cloned from), then the prototype's prototypes and so on.
In other words: there are no classes.
JavaScript actually has a nice tweak of that model: constructors. Not only can you create objects by copying existing ones, you can also construct them "out of thin air", so to speak. If you call a function with the new keyword, that function becomes a constructor and the this keyword will not point to the current object but instead to a newly created "empty" one. So, you can configure an object any way you like. In that way, JavaScript constructors can take on one of the roles of classes in traditional class-based OO: serving as a template or blueprint for new objects.
Now, JavaScript is a very powerful language, so it is quite easy to implement a class-based OO system within JavaScript if you want to. However, you should only do this if you really have a need for it and not just because that's the way Java does it.
ES2015 Classes
In the ES2015 specification, you can use the class syntax which is just sugar over the prototype system.
class Person {
constructor(name) {
this.name = name;
}
toString() {
return `My name is ${ this.name }.`;
}
}
class Employee extends Person {
constructor(name, hours) {
super(name);
this.hours = hours;
}
toString() {
return `${ super.toString() } I work ${ this.hours } hours.`;
}
}
Benefits
The main benefit is that static analysis tools find it easier to target this syntax. It is also easier for others coming from class-based languages to use the language as a polyglot.
Caveats
Be wary of its current limitations. To achieve private properties, one must resort to using Symbols or WeakMaps. In future releases, classes will most likely be expanded to include these missing features.
Support
Browser support isn't very good at the moment (supported by nearly everyone except IE), but you can use these features now with a transpiler like Babel.
Resources
Classes in ECMAScript 6 (final semantics)
What? Wait. Really? Oh no! (a post about ES6 classes and privacy)
Compatibility Table – Classes
Babel – Classes
I prefer to use Daniel X. Moore's {SUPER: SYSTEM}. This is a discipline that provides benefits such as true instance variables, trait based inheritance, class hierarchies and configuration options. The example below illustrates the use of true instance variables, which I believe is the biggest advantage. If you don't need instance variables and are happy with only public or private variables then there are probably simpler systems.
function Person(I) {
I = I || {};
Object.reverseMerge(I, {
name: "McLovin",
age: 25,
homeState: "Hawaii"
});
return {
introduce: function() {
return "Hi I'm " + I.name + " and I'm " + I.age;
}
};
}
var fogel = Person({
age: "old enough"
});
fogel.introduce(); // "Hi I'm McLovin and I'm old enough"
Wow, that's not really very useful on it's own, but take a look at adding a subclass:
function Ninja(I) {
I = I || {};
Object.reverseMerge(I, {
belt: "black"
});
// Ninja is a subclass of person
return Object.extend(Person(I), {
greetChallenger: function() {
return "In all my " + I.age + " years as a ninja, I've never met a challenger as worthy as you...";
}
});
}
var resig = Ninja({name: "John Resig"});
resig.introduce(); // "Hi I'm John Resig and I'm 25"
Another advantage is the ability to have modules and trait based inheritance.
// The Bindable module
function Bindable() {
var eventCallbacks = {};
return {
bind: function(event, callback) {
eventCallbacks[event] = eventCallbacks[event] || [];
eventCallbacks[event].push(callback);
},
trigger: function(event) {
var callbacks = eventCallbacks[event];
if(callbacks && callbacks.length) {
var self = this;
callbacks.forEach(function(callback) {
callback(self);
});
}
},
};
}
An example of having the person class include the bindable module.
function Person(I) {
I = I || {};
Object.reverseMerge(I, {
name: "McLovin",
age: 25,
homeState: "Hawaii"
});
var self = {
introduce: function() {
return "Hi I'm " + I.name + " and I'm " + I.age;
}
};
// Including the Bindable module
Object.extend(self, Bindable());
return self;
}
var person = Person();
person.bind("eat", function() {
alert(person.introduce() + " and I'm eating!");
});
person.trigger("eat"); // Blasts the alert!
Disclosure: I am Daniel X. Moore and this is my {SUPER: SYSTEM}. It is the best way to define a class in JavaScript.
var Animal = function(options) {
var name = options.name;
var animal = {};
animal.getName = function() {
return name;
};
var somePrivateMethod = function() {
};
return animal;
};
// usage
var cat = Animal({name: 'tiger'});
Following are the ways to create objects in javascript, which I've used so far
Example 1:
obj = new Object();
obj.name = 'test';
obj.sayHello = function() {
console.log('Hello '+ this.name);
}
Example 2:
obj = {};
obj.name = 'test';
obj.sayHello = function() {
console.log('Hello '+ this.name);
}
obj.sayHello();
Example 3:
var obj = function(nameParam) {
this.name = nameParam;
}
obj.prototype.sayHello = function() {
console.log('Hello '+ this.name);
}
Example 4: Actual benefits of Object.create(). please refer [this link]
var Obj = {
init: function(nameParam) {
this.name = nameParam;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var usrObj = Object.create(Obj); // <== one level of inheritance
usrObj.init('Bob');
usrObj.sayHello();
Example 5 (customised Crockford's Object.create):
Object.build = function(o) {
var initArgs = Array.prototype.slice.call(arguments,1)
function F() {
if((typeof o.init === 'function') && initArgs.length) {
o.init.apply(this,initArgs)
}
}
F.prototype = o
return new F()
}
MY_GLOBAL = {i: 1, nextId: function(){return this.i++}} // For example
var userB = {
init: function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var bob = Object.build(userB, 'Bob'); // Different from your code
bob.sayHello();
To keep answer updated with ES6/ ES2015
A class is defined like this:
class Person {
constructor(strName, numAge) {
this.name = strName;
this.age = numAge;
}
toString() {
return '((Class::Person) named ' + this.name + ' & of age ' + this.age + ')';
}
}
let objPerson = new Person("Bob",33);
console.log(objPerson.toString());
I think you should read Douglas Crockford's Prototypal Inheritance in JavaScript and Classical Inheritance in JavaScript.
Examples from his page:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Effect? It will allow you to add methods in more elegant way:
function Parenizor(value) {
this.setValue(value);
}
Parenizor.method('setValue', function (value) {
this.value = value;
return this;
});
I also recommend his videos:
Advanced JavaScript.
You can find more videos on his page: http://javascript.crockford.com/
In John Reisig book you can find many examples from Douglas Crockfor's website.
Because I will not admit the YUI/Crockford factory plan and because I like to keep things self contained and extensible this is my variation:
function Person(params)
{
this.name = params.name || defaultnamevalue;
this.role = params.role || defaultrolevalue;
if(typeof(this.speak)=='undefined') //guarantees one time prototyping
{
Person.prototype.speak = function() {/* do whatever */};
}
}
var Robert = new Person({name:'Bob'});
where ideally the typeof test is on something like the first method prototyped
If you're going for simple, you can avoid the "new" keyword entirely and just use factory methods. I prefer this, sometimes, because I like using JSON to create objects.
function getSomeObj(var1, var2){
var obj = {
instancevar1: var1,
instancevar2: var2,
someMethod: function(param)
{
//stuff;
}
};
return obj;
}
var myobj = getSomeObj("var1", "var2");
myobj.someMethod("bla");
I'm not sure what the performance hit is for large objects, though.
var Student = (function () {
function Student(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = firstname + " " + lastname;
}
Student.prototype.sayMyName = function () {
return this.fullname;
};
return Student;
}());
var user = new Student("Jane", "User");
var user_fullname = user.sayMyName();
Thats the way TypeScript compiles class with constructor to JavaScript.
The simple way is:
function Foo(a) {
var that=this;
function privateMethod() { .. }
// public methods
that.add = function(b) {
return a + b;
};
that.avg = function(b) {
return that.add(b) / 2; // calling another public method
};
}
var x = new Foo(10);
alert(x.add(2)); // 12
alert(x.avg(20)); // 15
The reason for that is that this can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.
Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!
You probably want to create a type by using the Folding Pattern:
// Here is the constructor section.
var myType = function () {
var N = {}, // Enclosed (private) members are here.
X = this; // Exposed (public) members are here.
(function ENCLOSED_FIELDS() {
N.toggle = false;
N.text = '';
}());
(function EXPOSED_FIELDS() {
X.count = 0;
X.numbers = [1, 2, 3];
}());
// The properties below have access to the enclosed fields.
// Careful with functions exposed within the closure of the
// constructor, each new instance will have it's own copy.
(function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
Object.defineProperty(X, 'toggle', {
get: function () {
var before = N.toggle;
N.toggle = !N.toggle;
return before;
}
});
Object.defineProperty(X, 'text', {
get: function () {
return N.text;
},
set: function (value) {
N.text = value;
}
});
}());
};
// Here is the prototype section.
(function PROTOTYPE() {
var P = myType.prototype;
(function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
Object.defineProperty(P, 'numberLength', {
get: function () {
return this.numbers.length;
}
});
}());
(function EXPOSED_METHODS() {
P.incrementNumbersByCount = function () {
var i;
for (i = 0; i < this.numbers.length; i++) {
this.numbers[i] += this.count;
}
};
P.tweak = function () {
if (this.toggle) {
this.count++;
}
this.text = 'tweaked';
};
}());
}());
That code will give you a type called myType. It will have internal private fields called toggle and text. It will also have these exposed members: the fields count and numbers; the properties toggle, text and numberLength; the methods incrementNumbersByCount and tweak.
The Folding Pattern is fully detailed here:
Javascript Folding Pattern
Code golf for #liammclennan's answer.
var Animal = function (args) {
return {
name: args.name,
getName: function () {
return this.name; // member access
},
callGetName: function () {
return this.getName(); // method call
}
};
};
var cat = Animal({ name: 'tiger' });
console.log(cat.callGetName());
MooTools (My Object Oriented Tools) is centered on the idea of classes. You can even extend and implement with inheritance.
When mastered, it makes for ridiculously reusable, powerful javascript.
Object Based Classes with Inheritence
var baseObject =
{
// Replication / Constructor function
new : function(){
return Object.create(this);
},
aProperty : null,
aMethod : function(param){
alert("Heres your " + param + "!");
},
}
newObject = baseObject.new();
newObject.aProperty = "Hello";
anotherObject = Object.create(baseObject);
anotherObject.aProperty = "There";
console.log(newObject.aProperty) // "Hello"
console.log(anotherObject.aProperty) // "There"
console.log(baseObject.aProperty) // null
Simple, sweet, and gets 'er done.
Based on the example of Triptych, this might even be simpler:
// Define a class and instantiate it
var ThePerson = new function Person(name, gender) {
// Add class data members
this.name = name;
this.gender = gender;
// Add class methods
this.hello = function () { alert('Hello, this is ' + this.name); }
}("Bob", "M"); // this instantiates the 'new' object
// Use the object
ThePerson.hello(); // alerts "Hello, this is Bob"
This only creates a single object instance, but is still useful if you want to encapsulate a bunch of names for variable and methods in a class. Normally there would not be the "Bob, M" arguments to the constructor, for example if the methods would be calls to a system with its own data, such as a database or network.
I am still too new with JS to see why this does not use the prototype thing.
A base
function Base(kind) {
this.kind = kind;
}
A class
// Shared var
var _greeting;
(function _init() {
Class.prototype = new Base();
Class.prototype.constructor = Class;
Class.prototype.log = function() { _log.apply(this, arguments); }
_greeting = "Good afternoon!";
})();
function Class(name, kind) {
Base.call(this, kind);
this.name = name;
}
// Shared function
function _log() {
console.log(_greeting + " Me name is " + this.name + " and I'm a " + this.kind);
}
Action
var c = new Class("Joe", "Object");
c.log(); // "Good afternoon! Me name is Joe and I'm a Object"
JavaScript is object-oriented, but it's radically different than other OOP languages like Java, C# or C++. Don't try to understand it like that. Throw that old knowledge out and start anew. JavaScript needs a different thinking.
I'd suggest to get a good manual or something on the subject. I myself found ExtJS Tutorials the best for me, although I haven't used the framework before or after reading it. But it does give a good explanation about what is what in JavaScript world. Sorry, it seems that that content has been removed. Here's a link to archive.org copy instead. Works today. :P
//new way using this and new
function Persons(name) {
this.name = name;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
}
var gee=new Persons("gee");
gee.greeting();
var gray=new Persons("gray");
gray.greeting();
//old way
function createPerson(name){
var obj={};
obj.name=name;
obj.greeting = function(){
console.log("hello I am"+obj.name);
};
return obj;
}
var gita=createPerson('Gita');
gita.greeting();

Categories

Resources