Read JavaScript Advanced Programming third Edition sixth chapter object-oriented design--Create object

Source: Internet
Author: User
Tags hasownproperty



While the object constructor or object literal can be used to create a single object, the disadvantage is obvious: creating many objects with the same interface produces a lot of duplicate code.



Factory mode




1 function Createperson (name,age,job) {

2 var o=new Object ();

3 o.name=name;

4 o.age=age;

5 o.job=job;

6 o.sayname=function () {

7 alert (this.name);

8}

9 return o;

10}




 
One-by-one Var Person1=createperson ("Jim", "Teaching in Colleage");
var Person2=createperson ("Merry", "Study in Colleage");
Console.log (Person1.sayname==person2.sayname);


View Code




Resolves an issue that creates multiple objects, but does not solve the problem of object recognition.



Constructor mode





1//Constructor mode

2/*

3 You must use the new operator, which is a few steps

4 1 Create a new object

5 2 Assigning the scope of a constructor to a new object

6 3 executing the code in the constructor (adding properties to the new object)

7 4 return new object

8 */

9 function Personbyconstructor (name,age,job) {//start with uppercase letters by convention constructor

Ten this.name=name;

One by one this.age=age;

This.job=job;

This.sayname=function () {

alert (this.name);

15};

16}

 
The Var person3=new personbyconstructor ("John", "Software Engineer");
var person4=new personbyconstructor ("Greg", "Doctor");

Console.log (Person3 instanceof Personbyconstructor);//return True
Console.log (Person4 instanceof Personbyconstructor);


View Code



Creating a custom constructor means that its instance can be identified as a specific type in the future.



Any function, as long as it is called by the new operator, can be used as a constructor, otherwise it is the same as a normal function.





1 Personbyconstructor ("Lily", +, "Driver");//Add to Window

2 Window.sayname ();


4 var o=new Object ();

5 Personbyconstructor.call (O, "Kristen", "Nurse");

6 o.sayname ();


View Code



The constructor mode is useful, but each method is recreated on each instance.
You can move the method to the outside of the constructor, but if the object calls many methods, you need to define a number of global functions, so there is no encapsulation to say. This problem can be solved by prototype mode.



Prototype mode



Each function we create has a prototype attribute (prototype), which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type. Prototype is the prototype object of the object instance that was created by invoking the constructor. The advantage of using object prototypes is that all object instances share the properties and methods that it contains.



Understanding prototype Objects



Whenever an object is created, a prototype property is created for the function according to a certain rule, which points to the prototype object of the function. By default, all prototypes automatically get a constructor (constructor) property that contains a pointer to the function where the prototype property is located.





function Personbyprototype () {

}
personbyprototype.prototype={
Name: "Jim",
Age:21,
Job: "Teaching",
Sayname:function () {
Console.log (this.name);
}
}
var person5=new personbyprototype ();
Person5.sayname ();

var person6= new Personbyprototype ("Mick", +, "assitant");
Person6.sayname ();
Console.log (PersonByPrototype.prototype.isPrototypeOf (PERSON5));//Through prototype.isprototypeof To determine if Personbyprototype is a person5 prototype.
Console.log (Object.getprototypeof (person5). Name),//object.getprototypeof can easily get the prototype of the object, which is very important in the case of using the prototype to implement inheritance.


View Code



Whenever the code reads the properties of an object, it points to a search, with the target being a property with the given name. The search starts first from the object instance itself, returns the value of the property if found, and if not found, the search pointer points to the prototype object, looking for the property with the given name in the prototype object. Our modifications to the prototype will be reflected immediately.
When you add a new property to an object instance, this property masks the same name attribute in the prototype object, in other words, prevents us from accessing the properties in the prototype, but does not modify that property. However, using delete allows you to delete the properties in the instance, allowing us to access the properties in the prototype.





Console.log (Person6.hasownproperty ("name")); hasOwnProperty to determine whether a property is an instance or a prototype inheritance.
Console.log (Person5.hasownproperty ("name"));


View Code



Prototypes and in Operators
When used alone, the in operator returns True when the given property is accessible through the object, whether the attribute exists in an instance or in a prototype. As long as the in operator returns True, and hasOwnProperty returns FALSE, you can determine that the property is a property in the prototype.





function Hasprototypeproperty (name,obj) {
Return!obj.hasownproperty ("name") && ("name" in obj);
}


View Code



When you use the for-in loop, you return an enumerable property that is accessed through an object, including the properties in the instance and prototype objects.





For (Var prop in Person5)
Console.log (prop); Back to Name,age, job, Sayname


View Code



The dynamic nature of prototypes
The pointer in the instance only points to the prototype, not the constructor.



If you change the prototype to another object, it is equivalent to cutting off the connection between the constructor and the original object.



Problems with native objects



1 omitted the link to the constructor function



2 All properties in the prototype are shared by all instances.



Combining prototype mode with constructor mode



  The constructor pattern is used to define instance properties, prototype patterns, to define methods and shared properties.


 
unction PersonByConstructorAndPrototype(name,age,job){ this.name=name; this.age=age; this.job=job; this.friends=[];
    }
    PersonByConstructorAndPrototype.prototype={
        constructor:PersonByConstructorAndPrototype,
        sayName:function(){console.log(this.name);}
    } var person7=new PersonByConstructorAndPrototype("LiLei",12,"Student"); var person8 = new PersonByConstructorAndPrototype("LiuLei",13,"Student")
    person7.friends.push("LiuLei");
    person8.friends.push("LiLei");
    console.log(person7.friends.toString());
    console.log(person8.friends);
View Code



Dynamic Prototyping Mode



Developers with other OO language experiences are likely to be very confused when they see independent constructors and prototypes. The dynamic prototyping model is a solution to this problem by encapsulating all the information in the constructor, and by initializing the prototype in the constructor (only if necessary), while preserving the advantages of using both constructors and prototypes. In other words, you can determine whether a prototype needs to be initialized by checking that a method that should exist is valid.



Parasitic constructor mode



If the above methods are not applicable, parasitic patterns can be applied. The core idea of this pattern is to create a function that simply encapsulates the code that creates the object.


//Parasitic constructor mode
function PersonByParasitic(name,age,job){
var o=new Object();
O.name=name;
O.age=age;
O.job=job;
o.sayName=function(){
console.log(this.name);
}
Return o;
}
var friend=new PersonByParasitic("Nicholas",20,"Software Engineer");
friend.sayName();
var friend2=new PersonByParasitic("Nick",32,"");
friend2.sayName(); 
View Code


This pattern can create constructors for objects in special cases.



Secure constructor Mode



A prudent object means that there is no public property, and its method does not refer to the This object.


















Read JavaScript Advanced Programming third Edition sixth chapter object-oriented design--Create object


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.