JavaScript Object-Oriented learning notes--creating objects

Source: Internet
Author: User
Tags uppercase letter hasownproperty

Factory mode

This modulo value abstracts the process of creating a specific object de. Use functions to encapsulate the details of creating objects aye specific interfaces.

Createperson(name,age,job) {    var o=new Object (); o.name=name; o.age=age; o.job=job; o.sayname= function () {alert (return o;} var Person1=createperson ("Chiaki", +,"Software Engineer");p Erson2=createperson ("Wu", "Student");           

Features: can be called countless times, solve the problem of creating multiple similar objects, but did not solve the problem of object recognition (that is, how to know the type of an object).

Constructor mode

Create a custom constructor that defines a property method for the custom object type.

function     Personthis.name=name; this.age=age; this.job=job; this.sayname=function () {alert (this.name);};} var person1=new person ( "Chiaki", 21, "software Engineer"); //person1 constructor (constructor) properties point to Personvar person2= new person (20,//person2 constructor (constructor) property points to person         

Both Person1 and Person2 have a constructor (constructor) property that points to person.

alert (Person1.constructor==person);//Truealert (Person2.constructor==person);//true 

The difference between a constructor pattern and a factory pattern:

1, no display of the creation of objects;

2. Assign attributes and methods directly to the This object;

3, no return statement;

4, the constructor function name begins with an uppercase letter, the non-constructor function name starts with a lowercase letter;

5. A new instance of the constructor must be created using the person1=new operator, such as VAR ("Chiaki", "Web Engineer");

6. In the future, his instance can be identified as a specific type.

The difference and connection between the constructor and other functions: the invocation of the two is different; any function that is called with the new operator can be used as a constructor and not called by the new operator, which is not the same as a normal function.

//use the example above as a constructor using var person= new person (21,//chiaki//as a normal function call person (20, "Student"); Window.sayname (); //wu//call a function in the global scope, this object always points to the global object (that is, the browser's Window object) //in another object scope call var o=new object (); Person.call (O, "Lola", 21, "designer"); //uses call () to invoke the person () function in the scope of object o, and after the call O has all the properties of the person () function and the Sayname () method O.sayname (); //lola             

Cons: Each method is recreated on each instance.

alert (person1.sayname==person2.sayname);//false

WORKAROUND: Move the function definition outside the constructor, but this method may need to define multiple global functions that will cause the custom reference type to be unpackaged.

function person (name,ago,< Span class= "title" >job) {this.name=name; this.age=age; this.job; this.sayname=sayname;} function sayname () {alert ( this.name);} var person1=new person ( "Chiaki", 21, "software Engineer"); var person2=new person (20, "Student"); //person1 and Person2 objects share the same sayname function defined in the global scope          

Prototype mode

Each function we create has a property (prototype) attribute, which is a pointer to an object that contains properties and methods that can be shared by all instances of a particular type.

Person() {}person.prototype.name="Chiaki"; Person.prototype.age=21; person.prototype.job="Software Engineer"; Person.prototype.sayname=function () {alert (this.name);}; var person1=New Person ();p erson1.sayname ();  Chiakivar person2=New Person ();p erson2.sayname ();  Chiaki           

Write a picture description here

Creating a new function generates a prototype property for it according to a specific rule, which points to the prototype object of the function, which automatically obtains a constructor property that contains a pointer to the function where the prototype property is located. When the constructor is called to create a new instance, the inner part of the instance contains a pointer (internal property [[Prototype]]) that points to the constructor's prototype object.

The values stored in the prototype can be accessed through an object instance, but the values in the prototype cannot be overridden by an object instance (when a property is added to an object instance, this property masks the property of the same name saved in the prototype object).

Person() {}person.prototype.name="Chiaki"; Person.prototype.age=21; person.prototype.job="Software Engineer"; Person.prototype.sayname=function () {alert (this.name);}; var person1=new Person ();  var person2=New Person ();p erson1.name="Wu"; alert (person1.name);  wu--from instance//when alert () accesses Person1.name, a property named name is searched on that instance, then no prototype alert (person2.name) is searched; //chiaki--from prototype//when alert () accesses Person2.name, it searches for a property named name on that instance and continues to search for the prototype, where the Name property is found. 

Use the delete operator to completely remove an instance property:.

var person1=new Person ();  var person2=New Person ();p erson1.name="Wu"; alert (person1.name);  Wualert (Person2.name); //chiakiDelete Person1.name;alert (person1.name);  The chiaki//delete operator removed the person1.name, thus restoring the connection to the name attribute        in the prototype

You can use the hasOwnProperty () method to detect whether a property exists in an instance or exists in a prototype.

Alert (Person1.hasownproperty ("name"));  False//person1 In the instance does not have the name attribute person1.name="Wu";  Person1 overrides the Name property, that is, the Person1 instance has the name attribute alert (Person1.hasownproperty ("name"));  True//prototype with in operator : Used alone, in for-inloop. 

When used alone, the in operator returns True when the given property is accessible through the object, regardless of whether the attribute exists in an instance or in a prototype.

Alert (the attribute in instance), or False if there is a property in the instance that returns True.

functionPerson() {}person.prototype.name= "Chiaki"; Person.prototype.age=21; Person.prototype.job= "software Engineer"; Person.prototype.sayname=function () {alert (this.name);}; var person1=new person (); new person (); Alert (Person1.hasownproperty (//false//name attribute in prototype alert (in person1); //trueperson1.name= "name"); //true//after re-name property, the Person1 instance has the name attribute alert ( "name" in person1); //true              
The Hasprototypeproperty () method determines whether the accessed property exists in the prototype. var person =New person (), alert (Hasprototypeproperty (Perso,"name"));  Trueperson.name="Wu";//Override Person.name, the Name property in the prototype is masked, then the Name property accessed is from the instance Personalert (Hasprototypeproperty ( person,"name"); //false       

The in operator and the hasOwnProperty () method use both to determine whether a property is in an object or in a prototype.

Used in the for-in loop, returns all enumerable (enumerated) attributes that can be accessed through the object, including properties in the instance and properties in the prototype. Instance properties that are masked in a prototype that are not enumerable (that is, [[Enumerable]] is set to false) are also returned in the for-in loop (except for IE 8 and earlier versions).

var o={    Name:"Chiaki"};  For (ino) {    alert (prop);  Name}   

An earlier version of IE has a bug that causes instance properties that mask non-enumerable properties to not appear in the for-in loop.

The default non-enumerable properties and methods are: hasOwnProperty (), propertyisenumerable (), tolocalestring (), toString (), and valueof (); ECMASCRIPT5 also sets the [[Enumerable]] of the constructor and prototype properties to false.

The Object.keys () method takes an object as a parameter and returns an array of strings containing all the enumerable properties.

var keys=object.keys (Person.prototype); alert (keys); //"Name,age,job,sayname"var p1=New Person ();p 1.name="Wu";p 1.age=;  var p1keys=object,keys (p1); alert (P1keys); //"Name,age"      
Keys=object.getownpropertynames (person.  prototype); alert (keys);  "Constructor,name,age,job,sayname"   

Simpler prototype syntax:

person.prototype={} person() {}person.prototype={    name:' Chiaki ', age    : $, job:  "Software Engineer", Sayname:function () {alert (this.name);}} ;      

In the example above, we set Person.prototype to equal to a new object created as an object literal, at which point the constructor property no longer points to person. (Reason: person.prototype={} essentially completely overrides the default prototype object when the constructor person was created, so the constructor property becomes the constructor property of the new object "point to the Object constructor").

At this point, if the value of constructor is important, you can deliberately set it back to the appropriate value, as follows:

Funtion person () {}person.prototype={    Constructor:person,//Reset constructor property will cause its [[enumerable]] attribute to be set to true, Can be modified by Object.defineproperty () to a non-enumerable    name:"Chiaki", age    : $,    job:"Software Engineer",    Sayname:function () {        alert (this.name);}};     

The dynamics of the prototype: because the process of looking up values in a prototype is a search, any modifications we make to the prototype object can immediately be reflected from the instance-even if the prototype was modified before the instance was created.

var friend=new Person (); person.prototype.sayhi=function () {    alert ("HI");} Friend.sayhi (); //"HI"   

The connection between the instance and the prototype time is a pointer rather than a copy, so you can add properties and methods to the prototype at any time, and the modification can immediately react to all object instances. However, if the entire prototype object is rewritten, the connection between the constructor and the original prototype will be severed. The pointer in the instance only points to the prototype and not to the constructor.

Prototype object problem: 1, omitted to pass the initialization parameter for the constructor function, the result all instances will obtain the same property value by default; 2. The prototype object has a shared nature, and for properties that contain reference type values, if one of the two instances created by a prototype object modifies the property value of the reference type, The property value of the reference type that will result in another instance is also changed.

Person() {}person.prototype={    Constructor=person,    friends:["Lola","Cherry"],}var Person1 =new Person (); var person2=New Person ();p Erson1.friends.push ("van"); alert (person1.friends);  Lala,cherry,vanalert (Person2.friends); //lola,cherry,vanalert (person1.friends==person2.friends)//true        

Combining the constructor pattern with the prototype pattern

Constructor patterns are used to define instance properties, which are used to define methods and shared properties.

functionPerson(Name,age,job) {This.name=name;This.age=age;This.job=job;this.friends=[ "Lola",  "Cherry";} person.prototype={Constructor:person, sayname:function () {alert (var person1=new person ( "Chiaki", 21, "software Engineer"); var person2=new person (20, "Student");p Erson1.friends.push (//lola,cherry,vanalert (person2.friends); //lola,cherryalert (person1.friends==person2.friends); //false//friends is an instance attribute defined in the constructor alert (person1.sayname==person2.sayname); //trues//sayname () is defined in the prototype, has a sharing          

Dynamic Prototyping Mode

Encapsulates all information in a constructor, while preserving the advantages of using constructors and prototypes while initializing prototypes in constructors. That is, by examining whether a village method is valid to determine whether the prototype needs to be initialized.

Person(name,age,job) {    //attribute    if (this.sayname!="function") {//check Person.prototype.sayname=function () {alert (this.name);}}} var friend=new Person ("Chiaki", +,"Software Engineer"); Friend.sayname ();    

Parasitic constructor mode

Create a function to encapsulate the code that creates the object, and then return the newly created object.

Person(name,age,job) {    var o=new Object (); o.name=name; o.age=age; o.job=job; o.sayname=function ( {Alert (return o;} var friend=new Person ("Chiaki", +,"Software Engineer"); Friend.sayname ();  Chiaki          

The constructor returns a new object instance by default without returning a value, and you can override the value returned when the constructor is called by adding a return statement at the end of the constructor. The object returned by the constructor has no relation to the constructor or the stereotype property of the constructor.

Secure constructor Mode

Secure object: That is, there is no public attribute, and the method does not use this object. For use in a secure environment where this and new are disabled, or when data is being changed by other applications.

Person(name,age,job) {    //Create object to return    var o=//Add method o.sayname=return o;}    

The object created in this mode has no way to access the name value except using the Sayname method.

JavaScript Object-Oriented learning notes-creating objects (GO)

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.