The 6th chapter of JavaScript Advanced Program design object-oriented programming

Source: Internet
Author: User
Tags hasownproperty

6.1 Object Properties 6.1.1 Property type

1. Data properties

What we typically call a property is a data property, which is used to map a string name to a value

4 Attributes of data attributes: Configurable, enumerable, writable, value
To modify properties by default, you must use the Object.defineproperty () method
Object.defineproperty (object, property name, descriptor object)

var person =' name ', {  false,  ' Natsu '= ' Natsu12 '  //  non-strict mode is ignored, error is thrown in strict mode

After setting the configurable to false, you can no longer modify features other than writable

var person =' name ', {  false' name ', {   //  throws an error  true});

2. Accessor Properties

Accessor properties cannot be defined directly and must be defined by using Object.defineproperty, which is an accessor property that defines the get and set attributes.
The getter function is called when the accessor property is read, and the setter function is called when the accessor property is written and the new value is passed in.
4 properties of accessor properties: configurable, enumerable, get, set
Specifying only the Get function means that the property is read-only and cannot be written

/*The following instance causes data attributes _year and edition to change when the accessor property year is modified*/varBook ={_year:2014, Edtion:1};object.defineproperty (book,' Year ', {get:function() {    return  This. _year; }, set:function(newvalue) {if(NewValue > 2014) {       This. _year =NewValue;  This. edtion = newValue-2013;   }}); Console.log (book.year); //call the Get function when you read yearBook.year = 2015;//call the Set function when writing yearConsole.log (book.edtion);//2

6.2 Creating Objects 6.2.1 Factory mode

This pattern abstracts the process of creating concrete objects, although it solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (that is, how to know the type of an object).

function Createperson (name, age, Job) {  varnew  Object ();   = name;   = Age ;   = job;   function () {    Console.log (this. Name);  };   return o;} var = Createperson (' Nicholas ', Person1, ' software Engineer ');p erson1.sayname ();   // Nicholas

6.2.2 Constructor Mode

To create a new instance of person, you must use the new operator, which actually goes through the following four steps:
1. Create a new object;
2. Assign the scope of the constructor to the new object (so this point points to the new object)
3. Execute the code in the constructor (add properties for this new object)
4. Returning new objects

functionPerson (name, age, job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. Sayname =function() {Console.log ( This. Name); };}varPerson1 =NewPerson (' Nicholas ', ' software Engineer ');varPerson2 =NewPerson (' Greg ', ' Doctor ');/*the created object has a constructor property, which points to the constructor*/Console.log (Person1.constructor= = person);//true/*the object created is both an instance of the person and an instance of object, because all objects inherit from object*/Console.log (Person1instanceofperson);//trueConsole.log (Person1instanceofObject);//true

Creating a custom constructor means that it will be possible to identify its instance as a specific type in the future, which is where the constructor pattern is better than the factory pattern (Factory mode cannot know the type of the object).

Multi-identity of constructors

A constructor is also a function, which is called by the new operator, and it can be used as a constructor, no different from a normal function if it is not called through new.

//use as a constructor functionvarperson =NewPerson (' Nicholas ', ' software Engineer ');p erson.sayname (); //"Nicholas"//use as a normal functionPerson (' Greg ', ' Doctor ');//error in strict mode, this is bound to window object in non-strict modeWindow.sayname ();//"Greg"//called in the scope of another objectvaro =NewObject (); Person.call (O,' Kristen ', +, ' nurse '); O.sayname (); //"Kistten"
Problem with constructor mode

Each method of the constructor pattern is recreated on each instance, but it is not necessary to create two instances of the function that accomplish the same task (wasted space).

Console.log (Person1.sayname = = person2.sayname);  // false // shows that functions with the same name on different instances are not equal, but they are functions that accomplish the same task

6.2.3 Prototype mode

Instances created through the prototype schema share all the properties and methods in the prototype object.

 function   person () {} Person.prototype.name  = "Nicholas" ; Person.prototype.age  = 29; Person.prototype.job  = "Software Engineer" ;  Person.prototype.sayName  = function   () { Console.log ( this  .name);};  var  person1 = new   person ();  var  person2 = new    person (); Console.log (person1.sayname  = = person2.sayname); //  

As soon as a new function is created, a prototype property is automatically added to the function, pointing to the prototype object of the function.
The prototype object has a constructor property, which refers back to the new function, and the original prototype object only obtains the constructor property, and other methods inherit from object.
After the constructor is called to create a new instance, an __proto__ property is automatically added to the instance, pointing to the prototype object of the constructor.
In the above example, two person instances do not contain properties and methods, but can call Sayname, which is accomplished by looking up object properties from the prototype object.

When you read the properties of an object, you first search from the object instance itself, and then continue to search for the prototype object that __proto__ points to.

If we add a property with the same name to the instance, it will mask that property in the prototype .

functionPerson () {}person.prototype.name= "Nicholas"; Person.prototype.age= 29; Person.prototype.job= "Software Engineer"; Person.prototype.sayName=function() {Console.log ( This. name);};varPerson1 =NewPerson ();varPerson2 =NewPerson ();p erson1.name= "Greg";p erson1.sayname (); //"Greg"-from the examplePerson2.sayname ();//"Nicholas"-from the prototype

You can use the hasOwnProperty () method to determine if the property is an instance property, return True if the property is an instance property of the object itself, or False if it is from a prototype object.

// Take The example above Console.log (Person1.hasownproperty ("name"));  // trueconsole.log (Person2.hasownproperty ("name"));  // false Delete person1.name;person1.sayname ();   // "Nicholas"-from the prototype Console.log (Person1.hasownproperty ("name"));  // false

The In operator (PropertyName in object): Returns True whenever a property is accessible through an object, whether directly on an upward access or through a prototype.

For in: You can iterate through all of the objects accessed (including instances and prototypes), enumerable properties.

The dynamic nature of the prototype:
You can add properties and methods to your prototype at any time, and any modifications you make to the prototype object can be immediately reflected from the instance.

Note that overriding a prototype object causes the connection between the existing prototype and any previously existing object instances to be severed.

Problem with the prototype object: When a property containing a reference type value is included, all instances are forced to be shared.

For example, an attribute friends is an array, and Person2.friends is modified when a person1.friends.push element is added to the call.

6.2.4 combination using constructor mode and prototype mode

In the most common way, the constructor pattern is used to define instance properties (each instance itself is unique, not shared), whereas the prototype pattern is used to define methods and shared properties.

6.2.5 Dynamic Prototyping Mode

All information is encapsulated in the constructor, and the prototype is initialized in the constructor function.

function Person (name, age, Job) {  this. Name = name;    this. Age = Age ;   this. Job = job;   if (typeofthis. Sayname! = "Functin")    {//  in the case that the Sayname method does not exist, Before adding it to the prototype    function  () {      Console.log (this. Name);   }}}

In the above code, adding the Sayname method to the prototype will only be performed when the constructor is first called.

The 6th chapter of JavaScript Advanced Program design object-oriented programming

Related Article

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.