javascript--Object-oriented learning (prototype in-depth learning)

Source: Internet
Author: User
Tags hasownproperty

Previous article

New Year first, first say a new year one weeks after the happy, and then start my text. The last one mainly said that object-oriented, the creation of objects in three modes, Factory mode, constructor mode and prototype mode, which is more important is the prototype model. Prototype mode is the prototype object, this time on the prototype for a deep learning.

Content

One, in operator

First, let's look at the in operator. A property in an object can be accessed through the in operator. That is, we can use the in operator to see if this property is in the object, and whether the property is from an instance or a prototype.

Let's talk about two ways to use the in operator

1. Use alone: The object can be accessed by the property is returned true, whether in the object's strength or on the prototype.

function person () {}person.prototype.name = ' jiang '; Person.prototype.age = 19; Person.prototype.job = ' SF '; Person.prototype.sayName = function () {console.log (this.name);} var p1 = new Person (); ' Name ' in P1;//true

The Name property is detected by the in operator and the return value is true, which indicates that the Name property can be detected in an instance of P1, but when we initialize it, we do not give the instance a name attribute, which indicates that the property is from the prototype object.

P1.name= ' z '; Name ' in P1;//true

  This is still true when we add a name attribute to the instance. But it's obvious that this is a property from the instance. These two examples show that simply by using the in operator, it is not possible to know whether the properties we want to detect come from the prototype object or the instance itself.

P1.hasownproperty (' name ');//truedelete p1.name;p1.hasownproperty (' name ');//false

By calling the hasOwnProperty () method, it is possible to know whether this attribute exists in the instance itself, but it is not possible to know whether this attribute exists in the prototype . So you can know whether it comes from a prototype or an instance by encapsulating the two methods together.

function Hasprototypeproperty (obj, name) {return!obj.hasownproperty (name) && name in obj;} var p2 = new Person (); Hasprototypeproperty (P2, ' name ');//falsep2.name = ' Z '; Hasprototypeproperty (p2, ' name ');//true

As long as hasOwnProperty () returns false, it is possible to determine if this property is from the prototype, and if it returns true, it comes from an instance of the object.

2.for-in: Returns an enumerable property that can be accessed through an object, including the properties in the prototype and the instance. Instance properties that block non-enumerable properties in the prototype can also be returned in the for-in loop, and all developer-defined properties are enumerable.

var o = {tostring:function () {return "MyObject";}} For (Var prop in O) {if (prop = = ' toString ') {console.log (prop);//not shown in IE}}

Note: There is a bug in earlier versions of IE that masking instance properties of non-enumerable properties does not occur in the for-in loop

3.object.keys () method. By calling this method, you can return a string array of all the enumerable properties contained in the object

Returns an enumerable property string in all prototype objects
var keys = Object.keys (Person.prototype); Console.log (key);//name, age, job, Sayname returns the enumerable property in the instance var key = Object.keys (P1 ); Console.log (key);//name here to Know Getownpropertynames () method var keys1 = Object.getownpropertynames (Person.prototype); Console.log (key);//constructor,name, age, job, sayname//This method even the non-enumerable property constructor is displayed.

Second, the dynamic nature of the prototype

Dynamic means that the modifications we make on the prototype object are immediately reflected in the instance, even if the instance of the object was first created and then modified.

function Person () {} Person.prototype.name='Jiang'; Person.prototype.age= the; Person.prototype.job='SF'; Person.prototype.sayName=function () {Console.log ( This. Name);        }; varperson =NewPerson (); Person.prototype.sayHi=function () {Console.log ("Hi"); };//Add a function to the prototypePerson.sayhi (); 

In the example above, we first add properties and methods to the prototype of the person object, instantiate it, and then we modify the Person,prototype to add a method called Sayhi. We will always be able to access this method later through an instance, due to the loose relationship between the prototype and the instance. But if we refactor this object with another simpler prototype syntax, the effect will be different.

var friend = new person (); Person.prototype = {name: ' Jiang ', age:14,job: ' SF ', Sayname:function () {console.log (this.name);}}

This simple prototype syntax is reconstructed by the literal syntax, which is equivalent to redefining a new object, which, after refactoring, cuts off the connection between the prototype and the object, the prototype chain is broken, the constructor pointer in the prototype no longer points to the person, but instead points to object. As we have said before, when we declare a function, the prototype object is created at the same time, and the object automatically obtains the constructor attribute and points to the original function, which is tantamount to cutting off the connection between the two. But we can get the connection back by adding Constructor:person to the object. But if we call Friend.sayname (), we get an error because the original [[prototype]] in friend is no longer pointing to the original prototype object.

Before modification:

After modification:

Although the reconstructed prototype object toggles the relationship between an existing prototype and an instance that has already been created, the reference is still the original prototype.

Third, the prototype of the native object

What are native objects: Object, String, array, and so on are native objects, and these native reference types are in prototype mode, and methods are defined on the prototype of their constructors, such as Array.prototype can find the sort () method. The prototype of the native object allows you to not only get a reference to the default method, but also define the method on its prototype. But you'd better not do that.

Iv. Problems with prototype objects

It's not that the prototype is perfect, problem one: ignoring the parameter passing initialization parameter, the result is that all instances get the same value by default . Problem two: the problem of sharing is also the biggest problem.

function person () {}person.prototype ={name: ' Jiang ', aga:14,job: ' SF ', friend: [' s ', ' F '],sayname:function () {Console. Log (this.name);}} var p1 = new Person (), var p2 = new Person ();p 1.friend.push (' V '), Console.log (p1.friend);//"S", "F", "V" Console.log ( P2.friend);//"S", "F", "V"

There is no friend in the P1 attribute, so the search into the prototype has the same name attribute, so the value added in P1 is essentially added to the properties of the prototype, and the instance P2 also does not have this property, so P1 modification affects P2. This is certainly what we do not want to see, of course, shared functions we are willing to, and shared properties then the problem is big go, like everyone has their own privacy, but because of the problem of sharing, my privacy is violated, not like being a spy is as serious.

In the dead of night, it is time to go to bed, tonight's content is so. Good Night ~

javascript--Object-oriented learning (prototype in-depth learning)

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.