Choose Payment Option
Pay at store or pay when you receive the items.
5min series on Javascript OOP
This is a 5mins series of essential skills.
Programming Basics. All modern programming languages have the following basic constructs:
Using Javascript Console:
As a new programmer, probably you will be using some existing libraries that define Javascript classes. Here is how to extend an existing class called BClass. MyClass extends BClass and adds a new method or overrides an existing method.
/**
* @constructor {MyClass}
* @extend {BLass} */
var MyClass = function(p1, p2, p3){
// Make sure we create the right class
if( !(this instanceof MyClass)) return new MyClass(p1, p2, p3);
// must call the parent class constructor.
BClass.call(this, p1, p2);
// add your own attributes here
this.p3 = p3;
};
MyClass.prototype = Object.create(BClass.prototype); // extend BClass
MyClass.prototype.constructor = MyClass; // set the constructor property
// Now add new methods or override.
// Always use this approach to extend a superclass.
MyClass.prototype.newMethod = function(){
//….
};
// We can also override an existing method
/** @override */
MyClass.prototype.existingMethod = function(){
// your function content
}
// Here is how we use a class to create an object
var myobj = new MyClass(1, 2, 3); // create an instance of MyClass
What did we do here?
Notice the annotations used: @constructor, @extend, @override. See the reference section below for more annotations.
Now, more details on creating, using, and extending javascript classes.
Creating your own Namespace
if MYAPP is defined, just use an existing one. If not defined, create one
var MYAPP = MYAPP || {}; // you can now prefix all classes with this. We will omit this for readability here.
Creating a class called Person. It is just a function!
/** @constructor */
var Person = function(first, last, age, eyecolor) {
// This function will be called when a Person object is created.
// i.e., this is the constructor function.
// Attributes (properties of the class)
// If subclasses redefine these attributes, it will simply overwrite (replace) the values.
// Therefore, avoid defining methods that can be overridden by subclasses.
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
// function definition
// if defined like this and subclasses overrides, Person.fullName cannot be called.
this.fullName = function() {return this.firstName + " " + this.lastName;};
};
Override a method of a superclass. All classes are a subclass of Object class.
/** @override */
Person.prototype.toString = function() {
var ts = Object.prototype.toString.call(this); // call the superclass method
return ts + “ Person”;
};
This can be overridden by subclasses and Person retains its own version.
Person.prototype.description = function(){
};
Creating an object using the class
var john = new Person("John", "Doe", 50, "blue");
john.firstName; // access object properties
john.fullName(); // access object methods
Inherit from another prototype
var Employee = function(first, last, age, eyecolor, title){
Person.call(this, first, last, age, eyecolor); // call the superclass
this.title = title;
};
Employee.prototype = Object.create(Person.prototype); // Do not use “new Person ()”
Employee.prototype.constructor =Employee; // set constructor property
Overriding inherited methods. All objects inherit from Object class
Employee.prototype.toString = function() {
var ts = Person.prototype.toString.call(this); // call the superclass method
return ts + “ Employee”;
}
call() and apply()
// You can call methods of a Class/object directly.
// This is useful for callbacks and event handlers.
// Calling a prototype method with a context (object reference)
var toString = Object.prototype.toString;
toString.call(new Person); // [object Person]
Adding a new method to an existing object
john.name = function () {
return this.firstName + " " + this.lastName;
};
Adding a new property to an existing Class:
Person.prototype.nationality = "English";
Adding a new method to an existing Class:
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Callbacks, event handlers, this, and bind operator
// “this” in event handlers and callback functions might be undefined or incorrect.
// Always bind the target object to callback functions or event handlers to solve this.
Solving callback function problems
Person.prototype.saveData = function(){
// callServerToSave(this.data, callBack); // this doesn’t work
callServerToSave(this.data, callBack.bind(this)); // bind the target obj
function callBack(result){
this.result = result; // here this is undefined without bind.
}
}
function callServerToSave(data, callBack){
…. call some AJax function to save
// call back when we have data
callBack(result);
}
Solving event handlers in jQuery
Person.prototype.onClick = function(event){ var self = event.data.self; } // access the correct obj
Person.prototype.registerHandler = function(){
// method 1
$("#the-element").click($.proxy(function () {
// you can use original 'this'
},this)); // pass this
// method 2
$('#the-element').on('click', {self:this}, this.onClick); // pass this
}
Calling a method of an object directly using call and apply
var fullName = john.fullName(); // get a reference to a method
fullName(); // error here. “this” in the function is undefined.
fullName.call(john); // correct. Pass the object specifically. Now “this” refer to john.
Other useful operators for prototype
john instanceof Person; //true;
Person.prototype.constructor == Person; //true. Construction is the Person function
john.constructor == Person; //true
john.hasOwnProperty('firstName'); // true
john.hasOwnProperty('toString'); // returns false. Doesn't check inherited properties
The following two are identical
var userAccount = new Object ();
var userAccount = {}
Making sure that this points to the right thing regardless of how the object is instantiated can be difficult. However, there is a simple idiom to make this easier.
var Person = function(firstName) {
if (this instanceof Person) {
this.firstName = firstName;
} else {
// make sure we create a Person not something else.
return new Person(firstName);
}
}
Annotating JavaScript for the Closure Compiler
https://developers.google.com/closure/compiler/docs/js-for-compiler#tags
Originally from:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Encapsulation allows developers encapsulate both data and method into one package and hide details. This allows developers to inherit methods and use them without knowing the implementation details of the methods.
Abstraction allows developers hides all but the relevant data about an object in order to reduce complexity and increase efficiency. Specialization by inheritance and composition by using other objects as properties of an object help developers quickly abstract out the current problem at hand. This increases reusability of code.
Polymorphism allow developers use an identical interface (method names, such as add, subtract, multiplication) for different types of data and objects, such as Integer, Float, BigInt, Rational, Imaginary, which all provide identically named methods, such as add, subtract, multiplication methods. You can see immediate benefits.
Name | Comments | Date |
---|