JS object class properties, methods and how to create objects

Source: Internet
Author: User
Tags object object hasownproperty

Property

Constructor: A reference (pointer) to the function that created the object. For the object class, the pointer points to the original object () function.

Prototype: A reference to the object's prototype of the object. For all classes, it returns an instance of Object objects by default.

Method

hasOwnProperty: Determines whether an object has a specific property. The property must be specified with a string (for example, O.hasownproperty ("name")).

isPrototypeOf (object): Determines whether the object is a prototype of another object.

propertyIsEnumerable: Determines whether a given property can be enumerated with a for....in statement

ToString (): Returns the original string representation of the object. For the object class, ECMA-262 is not set for this value, so different ECMAScript implementations have different values

ValueOf (): Returns the original value that best fits the object. The value returned by the method is the same as the return value of ToString () for a class that needs to be

JavaScript Create objects

Create an object, and then give the object new properties and methods.

var box = new Object ();//Create an object box.name = ' Lee ';//Create a Name property and assign a value Box.age = 100;//Create an Age property and assign a value Box.run = function () {//Create a run () method and return a value of return this.name + this.age + ' running ... ';}; Alert (Box.run ());//Output properties and method values

The above creates an object and creates properties and methods, and this in the Run () method represents the box object itself. This is the most basic way of JavaScript to create objects, but there is a disadvantage to create a similar object, it will produce a lot of code.

var box2 = box;//Gets the box reference box2.name = ' Jack ';//directly changes the name attribute alert (Box2.run ()); Using Box.run () to find the name also changed var Box2 = new Object (); box2.name = ' Jack '; box2.age = 200;box2.run = function () {return THIS.N Ame + this.age + ' running ... ';}; Alert (Box2.run ());//To avoid confusion with box so as to maintain independence in order to solve the problem of multiple similar object declarations, we can use a method called Factory mode, which is to solve the problem of instantiating objects to create a large number of duplication.  function CreateObject (name, age) {//functions that are instantiated in a centralized var obj = new Object (); obj.name = Name;obj.age = Age;obj.run = function () { Return this.name + this.age + ' running ... ';}; return obj;} var = createobject (' Lee ', box1), var box2 = CreateObject (' Jack '); alert (Box1.run ()); Alert (Box2.run ()); First Instance//second instance//remain Independent

Factory mode solves the problem of repeating instantiation, but there is one problem, which is to identify the problem, because there is no way to figure out exactly which object they are.

Alert (typeof box1);//objectalert (Box1 instanceof Object);//true

Constructors (construction methods) can be used in ECMAScript to create specific objects. The type is in object.

function Box (name, age) {//constructor mode this.name = Name;this.age = Age;this.run = function () {return this.name + This.age + ' Running ... ';};} var box1 = new Box (' Lee ', ' n '), var box2 = new Box (' Jack ', 200); New Box () alert (Box1.run ()); alert (box1 instanceof Box); Clearly identified him from the Box

The method of using constructors, that is to solve the problem of repeated instantiation, but also solve the problem of object recognition, but the problem is that there is no new object (), why can instantiate Box (), where does this come from? Methods that use constructors, and methods that use Factory mode, they differ as follows:

1. The constructor method does not display the creation object (new object ());

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

3. There is no Renturn statement.

Constructor methods have some specifications:

1. The function name and instantiation construct name are the same and uppercase, (PS: non-mandatory, but it helps to distinguish between constructors and ordinary functions);

2. Create an object from a constructor, you must use the new operator. Now that you can create an object from a constructor, where does this object come from and where does new object execute? The following procedures are performed:

1. When the constructor is used and the new constructor (), the new Object () is executed in the background;

2. The scope of the constructor to the new object, which is the object created by new object (), and the This in the body of the function represents the object of new object ().

3. Execute the code within the constructor;

4. Returns the new object (returned directly from the background).

For the use of this, this is actually a reference to the current scope object. If this is the global scope, this represents the Window object, and if it is in the constructor body, it represents the object declared by the current constructor.

var box = 2; alert (this.box);//The only difference between the global representation of the window constructor and the normal function is that they are invoked in different ways. Simply, the constructor is also a function and must be called with the new operator, otherwise it is a normal function. var box = new Box (' Lee ', 100);//construct Mode call alert (Box.run ()); Box (' Lee ', +); var o = new Object (); Box.call (o, ' Jack ', ()) alert (O.run ()); Normal mode call, invalid//object impersonation Call

The question of methods (or functions) inside a constructor is explored, first to see if the two instantiated properties or methods are equal.

var box1 = new Box (' Lee ', 100);//pass consistent var box2 = new Box (' Lee ', 100);//ditto alert (Box1.name = = Box2.name);//true, the value of the property is equal to alert (b Ox1.run = = Box2.run);//false, the method is also a reference address alert (box1.run () = = Box2.run ());//true, the value of the method is equal because the parameters are consistent

The methods (or functions) in the constructor can be replaced with the new function () method, which results in the same effect, and proves that they are ultimately judged by the reference address, uniqueness.

function Box (name, age) {//new function () uniqueness this.name = name;  This.age = age; This.run = new Function ("return this.name + this.age + ' run ... ');}

We can guarantee the consistency of the reference address by using the method of binding the same function outside the constructor, but it is not necessary to deepen the learning to understand:

function Box (name, age) {this.name = name;  This.age = age; This.run = run;} function run () {//via outside call, ensure reference address consistent return THIS.name + this.age + ' running ... ';}

Although the global function run () is used to solve the problem of ensuring that the reference address is consistent, this approach introduces a new problem, the global this is the box itself when the object is called, and as a normal function call, this also represents window.

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

This is logically understood: prototype the prototype object of the object that was created by invoking the constructor. The benefits of using prototypes allow all object instances to share the properties and methods that it contains. That is, instead of defining the object information in the constructor, you can add the information directly to the prototype.

The function Box () {}//declares a constructor Box.prototype.name = ' Lee '; Box.prototype.age = 100; Box.prototype.run = function () {return this.name + this.age + ' running ... ';};

Compare the methods in the prototype to the same address:

var box1 = new Box (); Add attributes to the prototype//Add a method to the prototype var box2 = new Box (); alert (Box1.run = = Box2.run); True, the reference address of the method remains consistent

In the prototype schema declaration, there are two more properties, both of which are generated automatically when the object is created. The __proto__ property is a pointer to the prototype object that the instance points to, and it acts as the prototype property constructor of the constructor. With these two properties, you can access the properties and methods in the prototype. Ps:ie browser in script access __proto__ will not be recognized, Firefox and Google Browser and some other browsers can be recognized. Although it can be output, it cannot get internal information.

alert (box1.__proto__);//[object Object]

Determines whether an object points to a prototype object of the constructor, which can be tested using the isPrototypeOf () method.

Alert (Box.prototype.isPrototypeOf (Box));

Whenever an object is instantiated, it will point to the execution flow of the prototype pattern:

1. First find the property or method in the constructor instance, and if so, return immediately;

2. If not in the constructor instance, go to its prototype object, and if so, return; Although we can access the values saved in the prototype through the object instance, we cannot access the values in the prototype by overriding the object instance.

var box1 = new Box (); alert (box1.name);//lee, the value in the prototype Box1.name = ' Jack '; alert (box.1name);//jack, nearest principle, var box2 = new box (); alert (box2.name); Lee, the value in the prototype, hasn't been box1 modified.

If you want to Box1 can also continue to access the values in the prototype, you can delete the properties in the constructor, as follows:

Delete box1.name;//Remove attribute alert (box1.name);

How can I tell if a property is in an instance of a constructor or in a prototype? You can use the hasOwnProperty () function to verify that:

Alert (Box.hasownproperty (' name '));//Returns True in the instance, otherwise false

Constructor instance properties and prototype properties, 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.

Alert (' Name ' in box);//true, present in instance or in prototype

We can detect whether an attribute exists in an instance by using the hasOwnProperty () hasOwnProperty () method, or it can be used to determine whether an attribute exists in an instance or prototype. The combination of these two methods allows you to determine whether a property exists in the prototype.

function Isproperty (object, property) {///To determine if an attribute exists in the prototype return!object.hasownproperty && (properties in OB ject);} var box = new box (), Alert (Isproperty (box, ' name '))//true, if the prototype has [/task] in order to allow properties and methods to better reflect the effects of encapsulation, and reduce unnecessary input,  The creation of prototypes can be used in the literal way: function Box () {};  Box.prototype = {//Use the literal way name: ' Lee ', age:100, Run:function () {return this.name + this.age + ' running ... '; }};  

Using constructors to create prototype objects and to create objects using literals is basically the same, but there are some differences in the way that literal creation uses the constructor property to not point to an instance, but to object, which is the opposite of how the constructor is created.

If you want the constructor of the literal way to point to an instance object, you can do this:

Box.prototype = {constructor:box,//Direct force pointing can};

PS: The literal way why does constructor point to Object? Because box.prototype={}; This writing is actually creating a new object. Each time you create a function, you create it prototype, and the object automatically gets the constructor property. So, the new object's constructor overrides Box's original constructor, so it points to the new object, and the new object doesn't specify a constructor, so it defaults to object. The declaration of the prototype is sequential, so the rewritten prototype will cut off the previous prototype.

function Box () {}; Box.prototype = {constructor:box, name: ' Lee ', age:100,//prototype was rewritten run:function () {return this.name + this.age + ' Run ... ';}; Box.prototype = {age =};var box = new box (); Alert (Box.run ()); Declare here that//box is just the prototype of the original statement.

Prototype objects are not only used in the case of custom objects, ECMAScript built-in reference types can be used in this way, and the built-in reference types themselves use prototypes.

alert (Array.prototype.sort);//sort is the Array type's prototype method alert (String.prototype.substring);//substring is a String Type of prototype method String.prototype.addstring = function () {return this + ', was added! ‘;}; Alert (' Lee '. addstring ()); Add a method to a string type//this represents the string to invoke//Use this method

PS: Although it is particularly convenient to add methods to native built-in reference types, we do not recommend using this method. Because it can cause naming conflicts, it is not conducive to code maintenance. Prototype schema creation object also has its own shortcomings, it omits the constructor parameter initialization of the process, the disadvantage is that the initialized values are consistent. And the biggest drawback of the prototype is its greatest advantage, that is sharing. All of the properties in the prototype are shared by many instances, and the share is appropriate for the function and can also be used for attributes that contain basic values. However, if the property contains a reference type, there are some problems:

function Box () {}; Box.prototype = {constructor:box, name: ' Lee ', age:100, family: [' father ', ' mother ', ' sister '],//added an array property run:function () {return this.name + this.age + this.family;}}; var box1 = new Box (), Box1.family.push (' elder brother '), alert (Box1.run ()), var box2 = new box (), Alert (Box2.run ()); Add ' brother '/share in the instance trouble, also have ' elder brother '

PS: Data sharing, which causes many developers to abandon the use of prototypes, because each instantiation of the data needs to retain its own characteristics, and cannot be shared. To solve the problem of constructing parameters and sharing, you can combine constructor + prototype mode :

function Box (name, age) {///do not share using constructor this.name = name; this.age = age; family = [' father ', ' mother ', ' sister '];};   Box.prototype = {//shared using prototype mode Constructor:box, Run:function () {return this.name + this.age + this.family; }};

PS: This mixed mode is a good solution to the problem of the sharing of parameters and references. is a good way to create objects. Prototype mode, regardless of whether you invoke a shared method in the prototype, it initializes the method in the prototype, and when declaring an object, the constructor + prototype part feels weird, preferably encapsulating the constructors and prototypes together. In order to solve this problem, we can use dynamic prototype mode.

function Box (name, age) {//encapsulates all information into the function body this.name = name; this.age = age;  if (typeof this.run! = ' function ') {//only at first call initialization Box.prototype.run = function () {return this.name + This.age +      ' Running ... ';   }; }}var box = new box (' Lee ', ' n '); alert (Box.run ());

When the constructor is called for the first time, the run () method discovers that it does not exist and initializes the prototype. When the second call is made, it is not initialized, and the new object is created the second time, and the prototype is no longer initialized. This and the encapsulation are achieved, and the prototype method is shared, and the attributes remain independent.

if (typeof this.run! = ' function ') {alert (' first initialization ');//test with Box.prototype.run = function () {return this.name + this.  Age + ' running ... '; };} var box = new Box (' Lee ', ' + '), alert (Box.run ()), Alert (Box.run ()), var box2 = new Box (' Jack ', ' Max '), Alert (Box2.run ()); Alert ( Box2.run ()); First create object//First call//second call//second time object creation

PS: Using the dynamic prototype mode, be aware that you can no longer use the literal way to rewrite the prototype, because it will cut off the connection between the instance and the new prototype. The above explains the methods of object creation in various ways, and if none of these approaches satisfy the requirements, you can use the first pattern: the parasitic constructor.

function Box (name, age) {var obj = new Object ();  Obj.name = name;  Obj.age = age;  Obj.run = function () {return this.name + this.age + ' running ... ';   }; return obj;}

The parasitic constructor, in fact, is the Factory mode + constructor mode. This pattern is generic, but not object-relational, so this pattern is not recommended when you can use the previously mentioned pattern. Under what circumstances is it appropriate to use a parasitic constructor? Suppose you want to create a reference type that has an extra method. Since the previous description does not recommend direct String.prototype.addstring, it can be added by means of parasitic constructs.

function MyString (string) {var str = new string (string); str.addstring = function () {return this + ', was added!  ‘;  }; return str;} var box = new MyString (' Lee '); Alert (box.addstring ()); Much more tedious than adding directly to the reference prototype

In some secure environments, such as the use of this and new, this is not used in the constructor, where new is not used when the constructor is instantiated externally. This method of creation is called a secure constructor.

function Box (name, age) {var obj = new Object ();  Obj.run = function () {return name + age + ' running ... ';//Direct printing of parameters can}; return obj;} var box = box (' Lee ', 100); Alert (Box.run ());

PS: The safe constructor is similar to parasitic. Inheritance inheritance is a relatively central concept in object-oriented. Other Orthodox object-oriented languages implement inheritance in two ways: one is an interface implementation and one is inheritance. ECMAScript only supports inheritance, does not support interface implementations, and implements inheritance in a way that relies on the prototype chain.

function Box () {this.name = ' Lee ';} function Desk () {this.age = 100;} Desk.prototype = new Box (), var Desk = new Desk (), alert (desk.age), alert (desk.name), function Table () {this.level = ' AAAAA '; }table.prototype = new Desk (); var table = new table (); alert (table.name); Box construction//Direct call function//desk constructs//desc inherit box, through prototypes, form chains//Get inherited Properties//table construct//continuation prototype chain inherit//Inherit box and Desk

Prototype chain inheritance Flowchart

If you are instantiating a table, then there are age=100 in the Desk instance, and the same attribute age=200 in the prototype, what is the final result?

Desk.prototype.age = 200;//instances and prototypes contain age

PS: The above prototype chain inheritance is also missing a link, that is obejct, all the constructors are inherited from the obejct. Inheriting Object is done automatically and does not require the programmer to inherit it manually. What happens to their dependencies after an inherited instance?

Alert (table instanceof Object),//truealert (desk instanceof table),//false,desk is the Super Class alert for table (table instanceof Desk) ;//truealert (table instanceof Box);//true

In JavaScript, inherited functions are called supertype (parent class, base class, other language), and inherited functions are called subtypes (subclasses, derived classes). Inheritance also has previous problems, such as literal rewriting of a prototype that breaks relationships, uses a prototype of a reference type, and the subtype cannot pass parameters to the super type. In order to solve the problem that reference sharing and super type cannot be referenced, we adopt a technique called borrowing constructors, or become the technique of object impersonating (forgery object, classical inheritance) to solve these two problems.

function Box (age) {this.name = [' Lee ', ' Jack ', ' Hello '] this.age = age;} function Desk (age) {Box.call (this, age);//Object impersonating, to the super-type parameter}var Desk = new Desk, alert (desk.age), alert (desk.name);d Esk. Name.push (' AAA '); alert (desk.name); New data added, only for desk

Although the borrowing of constructors solves just two kinds of problems, there is no prototype, and reuse is impossible to talk about. Therefore, we need the prototype chain + borrow the constructor pattern, this pattern becomes the combinatorial inheritance .

function Box (age) {this.name = [' Lee ', ' Jack ', ' Hello '] this.age = age;} Box.prototype.run = function () {return this.name + this.age;}; function Desk (age) {Box.call (this, age);} Desk.prototype = new Box (), var Desk = new Desk, alert (Desk.run ()); Object impersonation//prototype chain inheritance

There is also an inheritance pattern called prototype inheritance , which uses prototypes and creates new objects based on existing objects without having to create custom types.

function obj (o) {//pass a literal function F () {}//creates a constructor F.prototype = o;//assigns the literal function to the prototype of the constructor return new F ();//eventually returns the instantiated construct function}var box = {name: ' Lee ', arr: [' elder brother ', ' sister ', ' sister ']};var box1 = obj (box); alert (box1.name); The literal object//pass Box1.name = ' Jack '; alert (box1.name); alert (Box1.arr); Box1.arr.push (' parent '); alert (Box1.arr); var box2 = obj ( box); alert (box2.name); alert (Box2.arr); The Pass//reference type is shared

Parasitic inheritance combines the prototype + factory model to encapsulate the process of creating objects.

function Create (o) {//Package creation process var f= obj (o); F.run = function () {return this.arr;//Similarly, the reference will be shared}; return F;}

Combined inheritance is the most common inheritance pattern for JavaScript, but there is a small problem with the combination of inheritance, which is that the super type is called two times during use: one is the creation of subtypes, and the other is inside the subtype constructor.

function Box (name) {this.name = name; This.arr = [' elder brother ', ' sister ', ' parents ']; Box.prototype.run = function () {return this.name;}; function Desk (name, age) {Box.call [this, name]; this.age = age;} Desk.prototype = new Box (); Call box for the second time//Call box for the first time

The above code is the previous combination of inheritance, then the parasitic combination inheritance, resolved the problem of two calls.

  

JS object class properties, methods and how to create objects

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.