Showing posts with label java script functions. Show all posts
Showing posts with label java script functions. Show all posts

Thursday, May 16, 2013

JavaScript Learning #5 - Extending Built-In Objects with Prototype

Prototype can also be used to extend JavaScript's built-in objects.
The displayed code uses an anonymous function to add the negate property to JavaScript's Number type; the new property reverses the sign of any numeric value.

Example:


var myValue = 345.62;

Number.prototype.negate = function() {
return -1* this;
};
console.log(myValue.negate());

Number.prototype.half = function() {
return this/2;
};

console.log(myValue.half());


Output:
-345.62

172.81

JavaScript Learning #4 - Using the 'prototype' keyword


A big advantage of using objects is the ability to re-use already-written code in a new context. JavaScript supports extending and inheriting objects via the prototypekeyword

Example:


function Person(personName){
this.name = personName;
this.info = "This person is called " + this.name;
this.showInfo = function(){
console.log(this.info);
};
}

Person.prototype.sayHello = function(){
console.log(this.name + " says Hello");
};

var name = prompt("Who are you?");
person1 = new Person(name);

person1.showInfo();
person1.sayHello();


Output:

This person is called kkondal
kkondal says Hello