JavaScript Object-Oriented Concept Essential Part2

1. Argument (kinda like polymophism in oop)
Every function in Javascript has a private varibale called arugments, which can be used to access all the arguments passed to the function without specifying them as parameters when defiend the function.
Ex. function testArg()
{
for(i =0; i}

testArg("argmentnaisni1","ajgajdskgl2");

2. Prototype
2.1 (kinda like static field of class)
prototype is a field of all object, ex, you can use:
function Square(){;} //
Square.prototype.size = 5;//
//then all Square object has a field of size which has value 5.
// but one can override prototype filed value, ex
function Square(){
this.size = 1;
}
Square.prototype.size = 5; //because prototytpe loads before the object constructor, so it's // //overrided to 1.

2.2 (use like Inheritance)
because prototype is shared by all objects constructed by the function, it can achieve inheritance.
Ex.
function Car()
{
this. doors = 4;
this. speed = 0;
this. brake = function(){this.speed -=20;}
}

function fastCar()
{
this. speed = 100;
}

fastCar.prototype = new Car(); // now the fast car has
// fastCar.prototype.doors = 4;
//fastCar.prototype.speed =0;
//fastCar.prototype.brake = function(){this.speed -=20;}
//those are inheritanced from Car()
//however, since this. speed =100; in fastCar;
//this override the speed of fastCar to be 100;

3. Every insatance of object has a constructor property.
It returns the Function object which create the instance.
Ex. var str = new String("i am string");
alert(str.constructor); //return native String() constructor

Ex2. convert primitive type to object:
function myFunc(param)
{
param = new param.constuctor(param);
}
//explanation:
// param.constructor() is the same as String();
//because String() is the constructor to create param
// so the constructor: String(" ") take param as parameter, return the String object, assign it //to variable param. now param is an object, which has build-in method like //param.substring();

评论

此博客中的热门博文

AVR Tutorial - Input / Output

AVR ADC Analog to Digital Converter

Introduction to REST