Simple analysis of objects and methods in JS

Source: Internet
Author: User
Tags first string

As we all know, the object in JS is the essence, do not understand the object is not understand JS.

So what's the object in JS?

In JS, almost everything is the object:

    1. Boolean, String,number can be an object (or native data is considered an object);
    2. Dates, Maths,regexps,arrays,funcitons, of course objects, these are the objects;

JS, all values, except native values, are objects; These native values include: strings,numbers (' 3.14 '), true,false,null and undefined

object is a variable that contains a variable, A JS variable can contain a single value, such as:

var person = "John Doe";

Similarly, an object is a variable, but it can contain many values, except that the values are represented as key-value pairs (name and value separated by a colon), and a JS object is a collection of named values.

var person = {firstName: "John", LastName: "Doe", Age:50, Eyecolor: "Blue"};

Object Properties

The named value, which is called an attribute in the JS object, is written like this:

Propertyvaluefirstnamejohnlastnamedoeage50eyecolorblue
    • PHP Associate Arrays
    • The dictionaries in Python
    • The hash table in C
    • Hash maps in Java
    • Hashes in Ruby and Perl

Object methods

A method is a behavior or an action that behaves on an object, and an object property can be a native value, another object, or a function. An object's method is an object that contains a function-defined property.

Fullnamefunction () {return this.firstname + "" + This.lastname;}

A JS object is a container of name-value pairs and methods that contain so-called attributes.

Create a JS Object

In JS you can define and create your own objects, there are different ways to create objects:

    • Using object literals
    • Using the New keyword
    • Define a constructor, and then instantiate the
    • In ES5, you can also use the object.create () function to create objects

Object Literal method: The simplest, one sentence defines and creates an object. The object literal is the series of key-value pairs held in curly braces.

var person = {firstName: "John", LastName: "Doe", Age:50, Eyecolor: "Blue"};

New Keyword Method:

var person = new Object ();p erson.firstname = "John";p erson.lastname = "Doe";p erson.age = 50;person.eyecolor = "Blue";

The above two examples are almost similar, and there is no need to use new Object (). For brevity, readability, and execution performance, the first (object literal method) is preferred.

Object Builder

These two methods are limited in many contexts, and they only create a single object. Sometimes, we like to have an "object type" that can create many types of objects, at which point the standard way to create an object type from an object constructor arises.

function person (first, last, age, eye) {    this.firstname = first;    This.lastname = last;    This.age = age;    This.eyecolor = eye;} var myfather = new Person ("John", "Doe", "Blue") and var mymother = new Person ("Sally", "Rally", "green");

The above method is an object constructor, and once you have it, you can create objects of the same kind

var myfather = new Person ("John", "Doe", "Blue") and var mymother = new Person ("Sally", "Rally", "green");

this keyword

In JS, what is called this is an object that "owns" the JS code. The value of this, when used in a function, is an object of "owning" the function; When used in an object, it is the object itself. The This keyword, which does not have its own value in an object constructor, is simply a substitute for a new object. The value of this will become a new object when the constructor is used to construct the object.

Note: This is not a variable, it is a keyword and you cannot change the this value.

JS constructor for built-in native objects

var x1 = new Object ();    A new Object Objectvar x2 = new String ();    A new String Objectvar x3 = new number ();    A new number Objectvar x4 = new Boolean ();   A new Boolean Objectvar x5 = new Array ();     A new Array objectvarx6 = new RegExp ();    A new REGEXP Objectvar x7 = new Function ();  A new Function objectvar x8 = new Date ();      A New Date Object

  The math () object is not in the list because math is a global object and the New keyword cannot be used in math.

And , as we all know, JS has native data type String,number, and a Boolean object version. There is no reason to create impetuous objects, the native value executes faster .

var x1 = {};            New Objectvar x2 = "";            New primitive Stringvar x3 = 0;             New primitive Numbervar x4 = false;         New primitive Booleanvar x5 = [];            New arrayobjectvarx6 =/()/           //new regexp Objectvar x7 = function () {};  New Function Object

 The JS object is mutable

Objects are mutable, and they are positioned by index rather than by value. If a person is an object, the following statement does not create a copy of the person.

var x = person;  This is not the create a copy of person.

Object x is not a copy of person, it is the person itself, so any change in X changes the person.

JS variable is immutable, variable (Mutable) is just a JS object, the following example.

var person = {firstName: "John", LastName: "Doe", Age:50, Eyecolor: "Blue"}var x = Person;x.age = ten;           This would change both X.age and Person.age

 Object Properties

attribute is the most important part of the JS object

    • property is the value associated with the JS object
    • JS object is a collection of unordered attributes
    • Properties can be changed or deleted, some are read-only

To access the JS attribute syntax:

Objectname.property          //person.ageobjectname["property"]       //person[' age ']objectname[expression]       //x = " Age "; Person[x], the expression must be equal to the property name Person.firstname + "is" + Person.age + "years-old"; person[' FirstName ' + ' is ' + person[' age ' + ' years old ';

For-in Loop through object property syntax:

For (variable on object) {    code to is executed}

Add Property

person.nationality = "中文版";

But you can not use the reserved word as the attribute name, using the JS naming rules.

Delete Property

var person = {firstName: "John", LastName: "Doe", Age:50, Eyecolor: "Blue"};d elete Person.age;   

The DELETE keyword removes the property value and itself, and the deleted attribute is no longer available until it is added. The delete operator is used for object properties and is not valid for variables or methods. Remember, however, that the delete operator does not apply to the properties of the predefined JS object, which blocks the application.

Property attributes

Property has a name, and there is a value. Value is one of the properties of the property, and the other property is: Enumerable,configurable,writable. These properties define how the properties are accessed (readable and writable)

In JS, all properties are readable, but only the properties of value can be changed (if and only if the property is writable). There are methods in ES5 for properties of all properties of getting and setting.

Prototype properties

JS objects inherit the properties of their prototypes, and the DELETE keyword does not delete inherited properties, but if you delete the properties of the prototype, this affects all objects of the inherited prototype.

Object methods

As mentioned earlier, the JS method is the behavior that behaves in the object. The JS method is a property that contains the function definition, that is, the method is the function that saves the object property.

To access the object method:

Methodname:function () {Code lines}//creates an object method Objectname.methodname ();//Access name = Person.fullname ();// The FullName property when called with a () will execute name = Person.fullname;//fullname when the Great () call returns the function definition

Using built-in methods

var message = "Hello world!"; var x = Message.touppercase ();//hello world!

Add a method (similar to adding a property)

function person (firstName, lastName, age, Eyecolor) {    this.firstname = firstName;      This.lastname = LastName;    This.age = age;    This.eyecolor = Eyecolor;    This.changename = function (name) {        this.lastname = name;    };}

Object Properties

All JS objects have a prototype (prototype), and the prototype is also an object. All JS objects inherit the properties and methods of their prototypes.

The prototype of the so-called Object.prototype is inherited by the object of literal or newobject construction;

The object that is constructed with the new Date () inherits Date.prototype.Object.prototype out of the top (top) of the prototype chain

So all JS objects inherit from Object.prototype.

Create a prototype

The standard approach is to use a constructor to create an object prototype:

function person (first, last, age, Eyecolor) {    this.firstname = first;    This.lastname = last;    This.age = age;    This.eyecolor = Eyecolor;}

 With the constructor, you can use the New keyword to create new objects from the same prototype.

var myfather = new Person ("John", "Doe", "Blue") and var mymother = new Person ("Sally", "Rally", "green");
Constructors are prototypes of the person object, and it is a good practice to capitalize the first letter to name the constructor function

Adding properties and methods to an object

Sometimes you want to add a new property or method to an existing object, to any given type of existing object, or to an object prototype.

myfather.nationality = "中文版";//Give an existing object, just myfather.name = function () {    return this.firstname + "" + This.las tname;};/ /Add a method, just for this object

Adding attributes to a prototype

person.nationality = "English";//cannot be added as a new attribute to an existing object, because the prototype is not an existing object. function person (first, last, age, Eyecolor) {    this.firstname = first;    This.lastname = last;    This.age = age;    This.eyecolor = Eyecolor;    this.nationality = "English"}//add attributes to the prototype and must be added inside the constructor. Prototype properties can have prototype values (default) function person (first, last, age, Eyecolor) {    this.firstname = first;    This.lastname = last;    This.age = age;    This.eyecolor = Eyecolor;    THIS.name = function () {return this.firstname + "" + This.lastname;};} Add method

Take advantage of prototype properties

The JS Prototype property allows you to add new attributes and new methods to the existing prototype, but keep in mind that you only change the properties you have, and don't move the properties of the standard JS object.

function person (first, last, age, Eyecolor) {    this.firstname = first;    This.lastname = last;    This.age = age;    This.eyecolor = Eyecolor;} Person.prototype.nationality = "中文版"; Person.prototype.name = function () {    return this.firstname + "" + this.lastname;};

  JS function definition

The JS function can be defined by the function keyword, and you can also define a function by using the functions declaration (declaration) and the function expressions (expression).

function declaration

function functionname (parameters) {  code to be executed}
The semicolon is used to separate the JS execution statement, because the function declaration is not an executable statement, so it is uncommon to end a function declaration with a semicolon

Function declarations are not executed immediately, they are "standby" and are executed later when called.

function expression

var x = function (A, b) {return a * b};//functions expression can be stored in a variable
var z = x (4, 3);//At this time, this variable can be used as a function//In fact, the above function is an anonymous function, the function stored in the variable does not have to have a name, they are called with the variable name, and the semicolon ends because it is part of an executable statement

function constructors

Functions can be defined using the JS embedded function constructor functions ()

var myFunction = new Function ("A", "B", "return A * b"), var x = MyFunction (4, 3);

In fact you don't have to, in JS it is not necessary to use the New keyword.

function promotion

Elevation is the default behavior of the JS move declaration to the top of the current scope, promoted for variable declarations and function declarations, so functions can be called after declaration. However, functions defined by function expressions are not promoted.

MyFunction (5);//25function myFunction (y) {    return y * y;}
Foo ();//vm747:1 uncaught Typeerror:foo is not a function (...)
var foo=function () {}

Self-executing functions

(function () {    var x = "hello!!";      I'll Invoke Myself}) ();

In fact, the above function is an anonymous self-executing function

function can be used in a value or in an expression

function MyFunction (A, b) {    return a * b;} var x = myFunction (4, 3), Var y= myFunction (4, 3) * 2;

function objects

The typeof operator returns as ' function ' in JS for functions, but the function is best described as an object, and the JS function has properties and methods.

function MyFunction (A, b) {    return arguments.length;} But when the function is called, the number of arguments is returned var txt = myfunction.tostring ();//The first string () method returns a string

A function is defined as a property of an object, and is called a method of an object;

A function is defined as a creation object and is called an object constructor.

function parameters (Parameters)

The JS function does not make any checks on the parameter values.

JS parameters and arguments: The formal parameter is the name in the function definition (names), and the argument is the true value of the function passed to (or received) (real values)

functionname (Parameter1, Parameter2, Parameter3) {    code to be executed}

Formal parameter rules: JS for formal parameters of the function definition does not distinguish between the data type, the actual argument does not do type checking, the number of actual parameters received do not check.

Parameter default: If the function loses an argument (less than the declared) when called, the missing value is set to: undefined. It is sometimes acceptable, but it is best to set a default value for the parameter.

function myFunction (x, y) {    if (y = = = undefined) {          y = 0;    }} If the function is called by too many arguments (redundant declarations). These arguments can take advantage of an argument object to get

Argument Object

JS has built-in objects called argument objects that contain a real parameter group when the function is invoked. At this point, you can simply use the function to find the most value in a data list.

x = Findmax (1, 123, +, +), function Findmax () {    var i;    var max =-infinity;    for (i = 0; i < arguments.length; i++) {        if (Arguments[i] > max) {            max = arguments[i];        }    }    return Max;} The sum of the input values of the statistic is x = SumAll (1, 123, X, I, A,), function SumAll () {    var i, sum = 0;    for (i = 0; i < arguments.length; i++) {        sum + = Arguments[i];    }    return sum;}

Arguments passed by value

A formal parameter, in a function call, is a function argument, and theJS argument is passed by value , and the function only knows the value, not the address of the argument.

If a function changes the argument value, the original value of the formal parameter is not changed. Changes to the parameters are not visible outside the function (not reflected).

Object is passed by reference, andthe object index in JS is a value, so the object is represented by index: If a function changes the properties of an object, this changes the original value. Changes to object properties are visible outside the function (reflected)

JS function call

Four ways, each way with this how to initialize to differentiate.

Function call: function code is not executed when defined, only when called. (A JavaScript function can be invoked without being called.)

function as function call

function MyFunction (A, b) {    return a * b;} MyFunction (ten, 2);           MyFunction (2) would return 20

The above function does not belong to any object, but JS has a default global object. The default global object in HTML is the HTML page itself, so the above function "belongs" to the HTML page. In the browser Page object is the browser window, the above function automatically becomes the window function, wood function and window. No function is the same.

This is a common way of calling functions, but not a good habit. Global variables, methods, or functions can easily cause naming conflicts and bugs in global objects.

Global objects

When a function is called without an owner object, the this value becomes the global object. The global object in the Web browser is browser window.

function MyFunction () {    return this;} MyFunction ();                Would return the Window object

Invokes a function that acts as a global object, causing the effect of making this value a global object. Therefore, it is easy to block your programming by using the Window object as a variable.

As a method call

As a method call

var myObject = {    firstName: "John",    lastName: "Doe",    fullname:function () {        return this.firstname + "" + This.lastname;}    } Myobject.fullname ();         Would return "John Doe"

The FullName method is a function that belongs to the object, and no object is the owner of the function. What is called this is an object with JS code, and this value points to myobject.

var myObject = {    firstName: "John",    lastName: "Doe",    fullname:function () {        return this;    }} Myobject.fullname ();          will return [Object Object] (the owner object); Call the function as a method of the object so that this points to the object itself

Called as a constructor function

If a function was previously called by the New keyword, he is called by a constructor. It looks like creating a new function, but because the JS function is the object, you actually create a new object.

This is a function constructor:function myFunction (arg1, arg2) {    this.firstname = arg1;    This.lastname  = arg2;} Thiscreates a new Objectvar x = new MyFunction ("John", "Doe"); x.firstname;                             would return "John"

The constructor's call creates a new object that inherits the properties and methods of his constructor. The This keyword does not have a value in the constructor, but when the constructor is called, the This value will be the new object created.

Called by the method of a function

JS functions are objects, JS function has properties and methods. Call () and apply () are JS's predefined function methods, all of which can invoke a function and must have the owner object as the first parameter (when called).

function MyFunction (A, b) {    return a * b;} MyObject = Myfunction.call (MyObject, 2);     would return 20function myFunction (A, b) {    return a * b;} MyArray = [Ten, 2];myobject = Myfunction.apply (MyObject, myArray);  would also return 20

Both are the owner objects (owner object) as the first argument, and the only difference is that call takes the function arguments in a decentralized way, and apply takes the function arguments as an array. In JS strict mode, the first argument in the called function is the value of this, even if the argument is not an object. In non-strict mode, if the first argument is null or undefined, it is replaced by the global object. With call and apply you can set the this value and invoke the function as a method of an existing object.

JS Closed Package

The JS variable can be a global or local scope, and local variables can be constructed using closures.

Global variables

A function can access all the variables defined therein:

function MyFunction () {    var a = 4;    Return a * A;}

And, a function can also access functions in its outer layer, like this:

var a = 4;function myFunction () {    return a * A;}

At this point A is a global variable, in which the global variable belongs to the Window object, and the global variable can be used and changed by the script in all pages; In the first example, a is a local variable, and local variables can only be used inside the functions that they define, and hidden from other functions and script code. Global and local variables of the same name are different variables, and changing one does not affect the other, and the variable is not declared with the Var keyword, which is usually global, even inside the function.

Variable life cycle

Global variables and your application, your window, your webpage, local variables are short-lived, when the function calls are made, when the call ends are deleted.

See the following example

var counter = 0;function Add () {    counter + = 1;} Add (), add (), add ();//The counter is now equal to 3function Add () {    var counter = 0;    Counter + = 1;} Add (), add (), add (),//The counter should now is 3, but it does not work!function Add () {    var counter = 0;    Function Plus () {counter + = 1;}    Plus ();        return counter; }//solve This problem

JS Closure (closure)

Do you remember calling functions yourself? What does this function do?

var add = (function () {    var counter = 0;    return function () {return counter + = 1;}}) (); Add (), add (); Add ();//The counter is now 3

Explanation: The variable add is declared as the return value of a self-invoking function, the self-executing function runs only once, the counter is set to 0, and the expression is returned. The add in this way becomes a function, and the perfect part is that it can access the counter within the scope of the parent. This is called a JS closure, which makes it possible for a function to have a private variable. Counter is protected by the scope of the anonymous function and can only be changed using the Add function.

In summary: A closure is a function that can still access the parent scope even if the parent function is closed.

Reference: http://www.w3schools.com/

Simple analysis of objects and methods in JS

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.