Objects and Prototypes in Javascript

Keywords: Java Javascript Attribute Programming


Javascript is an object-based language, but it is not a true object-oriented programming language because it does not have the concept of classes in its syntax.To understand object-based principles in javascript, you need to understand the objects and prototypes in javascript.This article will take you one by one, and after reading it, you will find the importance of understanding this principle in depth and saving time and space during development.

object

ECMA-262 defines an object as an unordered collection of attributes of which contains a primitive value, object, or function.This means that the object is an array of values without a particular order.In a more general sense, an object is actually a reference type, and a reference type in javascript is a data structure that organizes data and functions together.

1. Basic Methods of Object Creation

Using the new operator

<script>
    var user = new Object();              //Create an object using the new operator
        user.name = 'java-tree';        //Add Properties to Objects
        user.age = 1;
        user.address = 'Wuhan';
        alert(user.name + " " +user.address);//Return to'java-tree'in Wuhan, Hubei
</script>

JSON Method Creation

var user = {
        name:'java-tree',
        age:1,
        address:'Wuhan'    
};
alert(user.name + " " +user.address);//Return to'java-tree'in Wuhan, Hubei
u Traditional Assignment
var user = {};
user.name = 'java-tree';        //Add Properties to Objects
user.age = 1;
user.address = 'Wuhan';
alert(user.name + " " +user.address);//Return to'java-tree'in Wuhan, Hubei

2. Object-based operations

Call to property
One way of invoking attributes, the'. 'operator, has been used in the above object creation as follows:

alert(user.name + " " +user.address);//Return 'java-tree Wuhan'

Another way:

alert(user['name'] + " " +user['address']);//Return to'java-tree'in Wuhan, Hubei

Add methods to objects (direct internal additions and external calls)

var user = {
    name:'java-tree',        //Add Properties to Objects
    age:1,
    address:'Wuhan',
    showInfo:function(){//Add a method
alert(this.name+" "+this.age+" "+this.address);//Return to'java-tree 1 Wuhan, Hubei'    
    },
    showHello:showHello//Adding methods outside objects to objects
};
function showHello(){
    alert("Hello!");    
}

Delete Object Properties

var user = {
    name:'java-tree',  
    age:1,
    address:'Wuhan'
};
alert(user.name);//Return to'java-tree'
delete user.name;//Delete name property of user
alert(user.name);//Return to'undefined'

Common methods for creating objects
Previously, we also introduced the basic method of creating objects, which is called the basic method because it is intuitive, but if we need to create multiple objects of the same reference type, we need to write a lot of duplicate code, which is not appropriate in the actual development process and greatly increases the amount of code.The following describes the factory mode and constructor methods.
Factory Mode

function create(name, age) {
    var obj = new Object();
    obj.name = name;
    obj.age = age;
    obj.run = function () {
    return this.name +' '+ this.age;
    };
    return obj;
}
var obj1= create('A', 1);    //First instance
var obj2= create('B', 2);    //Second example
alert(obj1.run());
alert(obj1.run());

Factory mode solves the problem of a large number of duplicate codes, but it also has drawbacks - it is not possible to identify which object was created when identifying instances.

alert(typeof obj1);          //Object

Constructor

function User(name, age) {
    this.name = name;
    this.age = age;
    this.run = function () {
    return this.name  + ' '+this.age;
    };
}
//create object
var user1= new User('A', 1);
var user2= new User('B', 2);
//Object recognition
alert(user1 instanceof User);//true 

The constructor method solves the problem of duplicate instantiation and object recognition, but it also has some problems. Look at the following code:

alert(user1.run==user2.run);//The result returns isfalse

The result returns false, which means the method is actually a reference address.If we also create multiple objects repeatedly, the methods in each object open up new space in memory, which wastes more space.To solve this problem, the concept of prototype objects is introduced below.

Prototype object

Constructor method

Prototype Object Method

From the diagram above, you can see that all the objects created by User share the method show(), so "user1.show == user2.show;" returns the value true here.

function User(name,age){//Construction method
        this.name = name;//Object Properties
        this.age = age;
}
User.prototype.addr = 'Wuhan';//Add attributes to the prototype
User.prototype.show = function(){//Add Method to Prototype
        alert(this.name+'|'+this.age);    
};
var user1 = new User('A',1);//Create an instance
var user2 = new User('B',2);
user1.show();//Call show() method
user2.show();
alert(user1.show == user2.show);//Returning true indicates that the show method is shared

However, there is a question, if we add an attribute in the construction method, in the prototype, and in the instance, which attribute do we visit?
The priority of property calls here obeys the proximity principle: instance property > object property > prototype property, you can try it yourself.

There are two other ways to create prototype objects, one is to create dynamic prototype objects, and the other is to create literal objects.
Dynamic prototype object

function User(name,age){//Construction method
        this.name = name;//attribute
        this.age = age;
        this.addr = 'Enshi, Hubei';
        User.prototype.addr = 'Wuhan';//Add attributes to the prototype
        User.prototype.show = function(){//Add Method to Prototype
            alert(this.name+'|'+this.age+'|'+this.addr);    
        };
}
var user1 = new User('ZXC',22);//Create an instance
var user2 = new User('CXZ',21);

Dynamic prototyping objects are not much different than before, except that encapsulating methods and attributes together looks more intuitive.But if you study this code carefully, you will also find that there are problems with it. Every time you create an object, you will create a prototype again. Although there is no additional increase in the control, it does increase in time, because each time you re-create it, you only need to add an if judgment to solve this problem:

if(this.show==undefined){//If the run method has not been created
        User.prototype.show = function(){//Add Method to Prototype
            alert(this.name+'|'+this.age+'|'+this.addr);    
        };
}

This reduces unnecessary overhead.

Create prototypes literally

function User(name,age){
        this.name = name;
        this.age = age;
}
User.prototype = {
        addr : 'Wuhan',
        show : function(){
            alert(this.name+'|'+this.age+'|'+this.addr);
        }
};  
//Rewritten prototype
User.prototype = {
        other : 'Rewrite Prototype',
        show : function(){
            alert(this.addr);    
        }
};    

The point to note about the literal mode is reflected in the code above. Once created using the literal mode, the prototype can no longer be rewritten using the literal mode. Once the prototype is rewritten, all properties and methods defined in the original prototype will be cleared.

Posted by luke101 on Thu, 06 Jun 2019 10:20:26 -0700