Blanche
Engineer
Engineer
  • UID619
  • Fans2
  • Follows2
  • Posts59
Reads:858Replies:0

Object-oriented programming in JavaScript

Created#
More Posted time:Nov 10, 2016 9:59 AM
The JavaScript object is a dictionary.
In Java, the mentioned “object” refers to the instance of the class or structure. The object has different attributes and methods, depending on the templates that instantiate them (that is, the class). But JavaScript objects are not like this. In JavaScript, the object is only a group of name/value pairs. That is to say, we can view JavaScript objects as dictionaries containing the string keyword. We can use the “.” (dot) operator or the “[]” operator to obtain and set the attributes of the object. This is a common method used for processing dictionaries.


 1. Methods for creating objects
//Method 1
var    obj = new Object();
obj.name="randy";
//alert(obj.name);

//Method 2
var    obj = {};
obj.name="zhao";
//alert(obj["name"]);

//Method 3
var obj ={"name":"test"};
//alert(obj.name);


2. Methods for creating functions
function func1(str){
    alert(str);
  //alert(this.name); //The name is an attribute I added later. But it cannot be accessed in the fun1() function body, and this.name cannot be accessed either.
}

var func2 = function(str){
  alert("hello "+str);
}

var func3 = new Function("str","alert(str);");//You can construct any functions at runtime.

var func4 ={
  "firstname":"name1",
  "lastname":"zhao",
  "display":function(){
    alert(this.firstname+":"+this.lastname);
  },
  "display2":function(){
    alert(this.firstname);
  }
}


You can add attributes for the functions.
func1.name ="Dummy Text";
//alert(func1.name);


Features of functions in JavaScript:
Functions in JavaScript are objects. Every function has a method named call which calls the function as the first parameter of the method. That is to say, any object that is passed to the call method as the first parameter of the function will be the “this” value during the function call. This technology is very helpful for calling constructors of the base class.
Never call functions containing “this” but with no objects. Otherwise, it will violate the global namespace. Because in the call, “this” will reference the global objects, which is inevitably disastrous for your application.
 
3. Constructor
function DogConstructor(name) {
  this.name = name;
  this.respondTo = function(name) {
    if(this.name == name) {
      alert("Woof");
    }
  };
}


In the above constructors, we can find that every Dog instance has its own respondTo method replica, which is a waste; You only need one respondTo instance that can be shared by various Dog instances. This issue can be avoided by defining respondTo out of the Dog instance. But another issue persists: this will cause many global functions. The situation will get very serious with the increase of “classes”. So you can implement it using the method below.
function respondTo() {
// respondTo definition
}
function Dog(name) {
this.name = name;
// attached this function as a method of the object
this.respondTo = respondTo;
}


4. Prototype
Notes: There is originally no class in JavaScript.
In the object-oriented programming using JavaScript, the prototype object is a core concept.
Objects in JavaScript are created as the replicas of the existing example (that is, prototype) object and this name derives from this concept.
function Dog(){
    this.name ="Doggy";
}

Dog.prototype.display = function(){alert(this.name);}
Dog.prototype.toString = function() {return "name:"+this.name;}
var dog = new Dog();
alert(dog);


All the attributes and methods of this prototype object will be displayed as attributes and methods of the object created by the prototype constructors. We can say that these objects inherit the attributes and methods from their prototype objects.
var buddy = new Dog(“Buddy“);
The objects referenced by the buddy will inherit the attributes and methods from its prototype. The prototype of the buddy object derives from the attributes of the constructor (here it is the function Dog). In JavaScript, every function has an attribute named “prototype” and the attribute is used to reference the prototype object.
This prototype object also has an attribute named “constructor” which references the function itself in turn. This is a kind of loop reference.
Just as the Dog instance inherits from the Dog.prototype, the Dog.prototype also inherits from the Object.prototype. This makes all the Dog instances inherit the methods and attributes of Object.prototype. Every JavaScript object inherits a prototype chain, and all the prototype objects end at the Object.prototype. Note: The inheritance you've seen so far is the inheritance between activity objects. It is different from the common concept of inheritance. The latter refers to the inheritance between classes when a class is declared. Therefore, JavaScript inheritance features a more dynamic nature. It utilizes simple algorithms to implement this, as shown below: When you try to access the attributes/methods of an object, JavaScript will check whether this attribute/method is defined in the object. If no, it checks the object prototype. If still no, it checks the prototype of the object prototype, until it reaches Object.prototype.


5. Static methods
function DateTime() { }
    
  DateTime.now = function() {
    return new Date();
  };
  DateTime.now2 = new Date();

  //alert(DateTime.now());
  //alert(DateTime.now2);


6. Closure
function makeGreaterThanPredicate(lowerBound) {
    return function(numberToCheck) {
          return (numberToCheck > lowerBound) ? true : false;
      };
  }


Closure is a runtime phenomenon when an internal function (or an internal anonymous method in C#) is bound to the local variable of its external function. It is obvious that the internal function doesn't make much sense unless it can be accessed by the external function in some way. This internal anonymous function uses lowerBound which is a parameter passed to makeGreaterThanPredicate. According to the general rules of the scope, when the makeGreaterThanPredicate exits, the lowerBound exceeds the scope. But here, the internal anonymous function still carries the lowerBound and remains so after the makeGreaterThanPredicate has exited for a long time. This is the closure as we call it. Because the internal function closes the environment that defines it (that is, the parameters and local variables of the external function).
 
7. Private variables of the “class”
function Person(name, age) {
    this.getName = function() { return name; };
    this.setName = function(newName) { name = newName; };
    this.getAge = function() { return age; };
    this.setAge = function(newAge) { age = newAge; };
        
    var occupation;
    
    this.age =age;
    this.getOccupation = function() { return occupation; };
    this.setOccupation = function(newOcc) { occupation =newOcc; };

}
  Person.prototype.display = function() {
    // doesn’t work!
     alert(this.name);//unidefined
     alert(this.age); //ok
    // this one below works
    alert(this.getName()); //ok
};

  var person = new Person("Joe",24);
  person.display();


In the code, you can simply regard the name as the private variable.
 
8. Simulated namespace is equivalent to the package in Java.
var com = {};
// nested namespace “Examples”
com.randy = {};
com.randy.Pet = function(name) {    
    this.name = name;

};
com.randy.Pet.prototype.toString = function() {
  return this.name;
};
var pet = new com.randy.Pet("Yammer");

alert(pet);
Guest