JavaScript object creation, inheritance

Source: Internet
Author: User

Creating objects

There are many ways to create objects in JS, the first of which:

var New Object ();

The second way:

var obj1 = {}; // Object Face Quantity

The Third Way: Factory mode

function Person () {  varnew  Object ();   = ' xxx ';   =N;       return obj;  } var p1 = person (); typeof P1; // Object

Fourth Way: constructor mode

    var function (name,age,job) {        this. Name = name;   Assignment this         .         this. Job = job;          This function () {            returnthis. Name;        }    };

Through the pattern of the constructor, there are four steps to be experienced:

1: Create a new empty object
2: Assigns the scope of the constructor to an empty object (this points to the empty object)
3: Execute the code in the constructor (add properties to this object)
4: Return This object

    var New Person (' xx ', ' x ', ' engineer ');     var New Person (' Xxwy ', ' teacher ');

The fifth way, ES5 implementation, is actually the inheritance in the object.

var obj2 = Object.createobject (obj1);
constructor function
varperson =function(name) { This. Name =name;}//new operatorvarP1 =NewPerson (' xxx ');p 1.name; //XXX//normal function callPerson (' Sssss '); window.name;//sssss this point to window in non-strict mode//Call,apply Method Invocationvarobj = {}; Person.call (obj,' DDDDDDDDDD '); obj.name;//dddddddd

    var New Person (' wfx ', ' engineer ');     var New Person (' wy ', ' teacher ');     // Both of these objects have constructor (constructor) properties    Console.log (Person1.constructor = = = person);  // true    Console.log (Person2.constructor = = = person);  // true

However, it is common to judge whether an instance object belongs to the constructor by instanceof

instanceof // true instanceof // true

Constructors and normal functions have no difference in JS, the only difference is that they are called in different ways. The constructor is called through the new operator.

    varperson =function(name) { This. Name =name;    }; //constructor new operator    varP1 =NewPerson (' X '); P1.name;//x    //normal function callPerson (' d '); Window.name;//d in non-strict mode the browser Global object is window this points to window    //call Apply mode invocation        varobj =NewObject (); Person.call (obj,' DDD '); Obj.name; //DDD
Problems with constructors:
    // because the function in JS is an object, creating a new function is not an instance    of the same function. // even though the same method in the same constructor is a different object instance, the method is complete and consistent. There is a waste of memory    console.log (person1.sayname = = = Person2.sayname);   false
How to Improve:
1, creating a global function, the problem is that there is a need to create a large number of global functions, there is no encapsulation.
    var function (name) {        this. Name = name;          // this.sayname = function () {        //     return this.name;        // }this        . sayname = sayname;    };     function Sayname () {        returnthis. Name;    }

2, through the prototype

First we recognize prototypes, and when each function is created, it generates a prototype property, which is a pointer to a series of rules for each function. Point to an object that is a prototype object (function.prototype ). Adding properties or methods to this prototype object allows each shares the properties and methods on the prototype object. The prototype object will have a constructor property that points to the object's function (that is, the original function).

  var  Dog =   () {}; Dog.prototype.name  = ' dog '; //     shared properties  Dog.prototype.sayName = function  () {return  this . Name}; //     shared method  var  dog1 = new      Dog ();  var  dog2 = new   Dog (); Console.log (dog1.sayname  = = = Dog2.sayname); //  true  
JS has two methods to judge the object's relationship to its prototype object:

1.isprototypeof () determines whether a prototype object is a prototype object of the instance object

 varperson =function(){         This. Name = ' WFX ';        }; //Person.prototype.constructor = = person; TruePerson.prototype.name= ' WFX '; Person.prototype.age= 12; Person.prototype.sayName=function(){        return  This. Name;    }; varPerson1 =NewPerson (); varPerson2 =NewPerson (); Console.log (Person.prototype.isPrototypeOf (Person1));//trueConsole.log (Person.prototype.isPrototypeOf (Person2));//true

2.object.getprototypeof (obj) obtains the Obj prototype object

1     Console.log (object.getprototypeof (Person1) ===person.prototype); // true 2     Console.log (object.getprototypeof (Person2)); // Person.prototype 3 4     Console.log (Person1.name); // ' wfx '

Understanding prototype Objects:

Look at the picture first

As we said before, the prototype property is automatically generated when the function is created, which points to an object. In the Person.prototype (prototype object), a constructor property is automatically generated in the prototype object that points to the constructor that is the person

Each instance object will have an internal property [[prototype]], which points to the prototype object.

Add a Name property to the prototype object, a Sayname method.

This is where the Person1 instance object shares this property and method, and it also shares the constructor property.

1 person1.name; // Zhang San 2 person1.sayname (); // Zhang San 3 person1.constructor; //  Person

Here we add a Name property to the Person1 instance object,

Person1.name = ' pock ';

We changed the Name property of the Person1 object. But it does not change the Name property of the Person2.

Person2.name; // ' Zhang San 'person1.name; // ' Pock '

We can understand that an instance object will first look for its own property or method if it has a finite invocation of its own property or method, if it does not have a prototype chain (see below) to find out if the prototype object has that property or method, there is no call to continue to find the first level prototype object through the prototype chain, and so on until object.

A property that determines whether an attribute is an instance object itself can be passed hasownproperty ();
Person1.name = ' ddddd ';p erson1.hasownproperty (' name '); // true;

Determines whether a property is available in an instance object property through the in operator;
 in Person2; // true

Enumerating object properties using the for in

For-in returns the properties that an object can access

Object.keys (obj); Returns an object that can be enumerated and is the instance's own property.

Object.getownpropertynames (obj); Returns all properties of the object.

Problems with prototype objects

Because it is shared, it causes the reference data type to be shared

var function () {    = [1,23,4,4]; var New Person ();p 1.firends; // [1,23,4,4]; P2.firends; // [1.23,4,4]; // Modify P1.firendsp1.firends = [' a ']; // at the same time P2 was also modified. P2.firends; // [' A ']

That 's why we use Mixed mode .

//property in the constructorvarperson =function(name,age,job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. firends = [1,2,3,4,5];}//method in the prototype objectPerson.prototype ={Constructor:person, sayname:function(){return  This. Name}, Sayage:function(){return  This. Age}}

Inherited

。。。。。。。

JavaScript object creation, inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.