javascript--Object + function

Source: Internet
Author: User
Tags addall instance method object serialization hasownproperty

1. Complex data type Object
An object in ECMAScript is actually a collection of data (attributes) and functions (methods).
1) Create an object instance:
1. Create with constructor, new Object ()
var person = new Object ();
Person.name = "Briup";
Person.age = 22;

2. Using object literals notation
Use ': ' Between different attributes with ', ' Split, attribute name and attribute value
var person = {
Name: "Briup",
Age:22
};
2) Accessing object properties
1. dot notation, the right side must be a simple identifier named after the property name
Person.name
2. Bracket notation, in brackets must be an expression that evaluates to a string, you can access the property through a variable, if the property name contains a syntactically incorrect character, or if the property name uses a keyword or reserved word, you can use the Bracket person["first name"]
var a = "name";
Person[a]; Both person["name"]
person["First Name"]

3) Delete attributes
Delete simply disconnects the property from the host object and does not manipulate the properties in the property, and delete Deletes only its own property and cannot delete the inherited property. When destroying an object, to prevent memory leaks, traverse the properties in the object, and then delete all the properties.
Syntax: Delete property access expression
For example:
Delete stu.name//Remove the name attribute from student objects
4) Detection Properties
In detects whether a property is an object's own property or an inherited property, returns True, otherwise false
"ToString" in student
hasOwnProperty () detects if the given property is an object's own property, and returns false for the inherited property
var o = {
X:1
}
O.hasownproperty ("X"); True, X is the own property of O
O.hasownproperty ("Y"); Attribute y does not exist in False,o
O.hasownproperty ("toString"); False,tostring for inherited properties
propertyIsEnumerable () detects whether a given property is an object's own property, and that property is enumerable, and the properties that are usually created by JS code are enumerable, but you can use special methods to change the enumerable.
Student.propertyisenumerable ("toString")//false not enumerable
5) Object Properties and methods
Any properties and methods that the object type has also exist in other objects, and any object inherits from the object
Common methods in object:
hasOwnProperty (PropertyName);
Checks whether the given property name is an object's own property,
ToString ();
Returns the string representation of an object
ValueOf ();
Returns the string, numeric value, and Boolean representation of the object.
propertyIsEnumerable (PropertyName);
Checks whether a given property exists in the current object instance
Constructor
Save the user's function to create the current object
isPrototypeOf (object);
Check if the incoming object is a prototype
toLocaleString ();
Returns a string representation of the object that corresponds to the region of the execution environment
6) Serialization of objects
Object serialization refers to converting the state of an object to a string, or to deserializing, reverting a string to an object function, Regexp,error an object, and undefined values that cannot be serialized and deserialized.
Json.stringify (obj)
Serializes an object into a JSON string and can serialize only its own properties that can be enumerated.
Json.parse (JSONSTR)
Deserialization

2. Functions

0) Declaration Promotion:

function declaration promotion, all function declarations are promoted to the top of the current scope

function declaration---> function declaration is promoted

function FnName (ARG1,ARG2) {

function body

}

function Expressions---> function expressions are not promoted

var fnname=function () {

function body

};

Variable declaration Promotion

Alert ("A" in window);

var A; ===>var A;

Alert ("A" in window);

Only variable declarations are promoted and variable initialization is not promoted (that is, when variables are directly assigned, they are created during the execution phase).

var a=1; ===>var A;

A=1;

alert (a); Undefined

alert (b);//error

b=10;

var a=20;

When a variable is declared and initialized, JavaScript automatically splits the variable declaration and variable initialization

Why is there no elevation variable initialization?

Because this affects the value of the variable causing unpredictable results during code execution

You must know and understand that a function declaration overrides a variable declaration, but does not overwrite the variable class.

function value () {

return 1;

}

var value;

Alert (typeOf value); Function (typeof returns a String representing the type)

function declarations receive higher precedence even after the declaration of a variable is present in the function declaration

function value () {

return 1;

}

var value=1;

Alert (typeOf value); Number variable initialization overrides function declaration

var a=1; var A;

function foo () {function foo () {

a=10; function A () {}

function A () {} ===> a=10;

}                    }

Foo (); A=1;

alert (a); Foo ();

alert (a); 1
1) function as a value
Since the function name itself is a variable, the function can be used as a value (parameter, return value).
function Callother (Fun,args) {
Return fun (args);
}
Function Show (msg) {
Alert (msg);
}
Callother (show, "haha"); Show as Parameter
2) function as the return value
Eg: Multifunctional custom sorting function
function Mycompare (PRO) {
function is returned as a return value
return function (OBJ1,OBJ2) {
var val1 = Obj1[pro];
var val2 = Obj2[pro];
if (Val1<val2) {
return-1;
}else if (val1>val2) {
return 1;
}else {
return 0;
}
}
}
var data = [
{
Name: "AAA",
Age:12
},{
Name: "CCC",
Age:8
},{
Name: "BBB",
age:71
}
];
Console.log (data);
Data.sort (Mycompare ("Age"));
Console.log (data);
3) function Internal properties
1. Arguments: is a class array object that contains the arguments passed into the function, and the arguments object has a callee property that points to the function that owns the arguments object
Implementing the addition of multiple numeric types
var addall = function () {
Console.log (Arguments.callee = = AddAll);
arguments = [1,2,3,5];
var total = 0;
for (var key in arguments) {
Get value by index, key index 0,1,2,3
var value = Arguments[key];
Total +=value;
}
return total;
}
var result = AddAll (1,2,3,5,3,4);
Console.log ("The result is:" +result);
For example:
The factorial of NUM, using recursive functions
function factorial (num) {
if (num<=1) {
return 1;
}else{
return num * factorial (num-1);
Return num * Arguments.callee (NUM-1);
}
}
2. This: Refers to the Environment object on which the function is executed
Window.color = "Window";
var person = {
Color: "Person"
};

    function Saycolor () {
    alert (this.color);
   }
    Saycolor (); //window object is called, so pop up "window"
    Perso N.saycolor = Saycolor; Assign the method to the Person object
    person.saycolor ();//Use the Person object to invoke the method, which pops up the properties of the "person"
 4) function
        Length: Indicates the number of named arguments that the function expects to accept
   function say (msg) {}// Say.length 1 want to accept a parameter
   function Add (m,n) {}//add.length 2 want to accept two parameters
     & nbsp;  prototype: The true location of the Save instance method. It is important to customize reference data types and inheritance.
5) method of the function
   this-> the Environment object in which the function is located
   <script>
    var person = { br>     name: "Terry",
     add:function () {
    &NBSP;&NBSP
    }
    }
    person.add ();

    function Add (A, b) {
     alert (a+b);
   
    Add,//This->window
    =>
     Add.call (window,1,2);
   </script>
  
   apply: Parameter (the scope in which the function is run, the parameter array (array,arguments));   
   call : Parameters (the scope in which the function is run, the parameter list)
        Both of these methods function to invoke a function in a specific scope, which is actually equivalent to setting the value of this inside the function

Usage One:
function sum (m,n) {
return m+n;
}
function call (m,n) {
Return sum.apply (this,arguments);
Return Sum.call (This,m,n);
}
alert (call);
Usage Two:
The scope in which the expansion function is run
Window.color = "Window";
var person = {
Color: "Person"
};

function Saycolor () {
alert (This.color);
}
Saycolor.call (this);
Saycolor.call (window);
Saycolor.call (person);

3. Basic data type, reference data type
Variables for the base data type:
The actual values stored in the variable can be manipulated directly
The actual value is passed when the parameter is passed
Variables that reference the data type:
The object's memory space cannot be manipulated directly, and is actually a reference to the object being manipulated.
You can celestial pole love properties and methods for reference type variables, or you can change and delete their properties and methods
A reference address is passed when the parameter is passed.
Value passing
Copy of the value
Reference delivery
Copy of referenced address

var a = 3;
var P1 = {
Name: "Larry",
Age:14,
Gender: "Male",
};
function Changea (a) {
++a;//4
}
function ChangeName (p) {
b001
P.name = "Tom"
}
function Changep (p) {
p = b001
p = b002
p = {
Name: "Jacky",
Age:14,
Gender: "Male",
}
}
Console.log (p1);//b001 Object {name: "Larry", Age:14, Gender: "Male"}
ChangeName (p1); b001
Changep (p1);
Console.log (p1);//b001 Object {name: "Tom", Age:14, Gender: "Male"}

Console.log ("Before A:" +a); 3
Changea (a);
Console.log ("After a:" +a); 3

javascript--Object + function

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.