Prototype Object Learning

Source: Internet
Author: User
Tags tojson

Object is used by Prototype as a namespace; that is, it just keeps a few new methods together, which are intended for namespaced access (I. e. starting with "Object .").
The namespace mentioned above is equivalent to the static class in C #. It provides the meaning of tool functions, and the namespace in C # should not be a concept. Because the namespace in C # will not follow the method directly, it must be an object and then calling the method, but it is similar to the namespace in C ++.
Clone
Extend
Inspect
IsArray
IsElement
IsFunction
IsHash
IsNumber
IsString
IsUndefined
Keys
ToHTML
ToJSON
ToQueryString
Values
Copy codeThe Code is as follows:
// Create an Object using an anonymous function call
(Function (){

// Obtain the string expression of the type. (Prototype Learning-tool function learning ($ method) Detailed descriptions are provided in this log.
Function getClass (object ){
Return Object. prototype. toString. call (object)
. Match (/^ \ [object \ s (. *) \] $/) [1];
}

// Inheritance method. A simple copywriting mechanism is to copy all the attributes and methods in source to destination. If it is a reference type, then source and destination point to the same address
Function extend (destination, source ){
For (var property in source)
Destination [property] = source [property];
Return destination;
}

// Returns the string expression of the object.
Function inspect (object ){
Try {
If (isUndefined (object) return 'undefined ';
If (object = null) return 'null ';
Return object. inspect? Object. inspect (): String (object );
} Catch (e ){
If (e instanceof RangeError) return '...';
Throw e;
}
}

// Return the JSON (JavaScript object Notation) of the Object)
Function toJSON (object ){
Var type = typeof object;
Switch (type ){
Case 'undefined ':
Case 'function ':
Case 'unknown ': return;
Case 'boolean': return object. toString ();
}

If (object = null) return 'null ';
If (object. toJSON) return object. toJSON ();
If (isElement (object) return;

Var results = [];
For (var property in object ){
Var value = toJSON (object [property]);
If (! IsUndefined (value ))
Results. push (property. toJSON () + ':' + value );
}

Return '{' + results. join (',') + '}';
}

// Return the query string, for example, param1 = value1 between m2 = value2
Function toQueryString (object ){
Return $ H (object). toQueryString ();
}

// Returns an HTML string.
Function toHTML (object ){
Return object & object. toHTML? Object. toHTML (): String. interpret (object );
}

// Obtain all the keys of the object
Function keys (object ){
Var results = [];
For (var property in object)
Results. push (property );
Return results;
}

// Obtain all object values
Function values (object ){
Var results = [];
For (var property in object)
Results. push (object [property]);
Return results;
}

// Copy all the attributes and methods in the object to an empty object and return
Function clone (object ){
Return extend ({}, object );
}

// Determine whether the object is a basic DOM Element.
Function isElement (object ){
Return !! (Object & object. nodeType = 1 );
}

// Determine whether the object is an array
Function isArray (object ){
Return getClass (object) = "Array ";
}

// Determine whether the object is a Prototype Hash object
Function isHash (object ){
Return object instanceof Hash;
}

// Determine whether the object is a function
Function isFunction (object ){
Return typeof object = "function ";
}

// Determine whether the object is a string
Function isString (object ){
Return getClass (object) = "String ";
}

// Determine whether the object is a number
Function isNumber (object ){
Return getClass (object) = "Number ";
}

// Determine whether the object has been defined
Function isUndefined (object ){
Return typeof object = "undefined ";
}

// Return the Object
Extend (Object ,{
Extend: extend,
Inspect: inspect,
ToJSON: toJSON,
ToQueryString: toQueryString,
ToHTML: toHTML,
Keys: keys,
Values: values,
Clone: clone,
IsElement: isElement,
IsArray: isArray,
IsHash: isHash,
IsFunction: isFunction,
IsString: isString,
IsNumber: isNumber,
IsUndefined: isUndefined
});
})();

Inspect Method:
Copy codeThe Code is as follows:
Object. inspect () //-> 'undefined'
Object. inspect (null) //-> 'null'
Object. inspect (false) //-> 'false'
Object. inspect ([1, 2, 3]) //-> '[1, 2, 3]'
Object. inspect ('hello') //-> "'hello '"

ToJSON method:
Note that there is a recursive call process var value = toJSON (object [property]). Finally, a JSON string is returned. The following is an example:
Copy codeThe Code is as follows:
Var data = {name: 'viole', occupation: 'character ', age: 25, pets: ['frog', 'rabbit']};
/* '{"Name": "Violet", "occupation": "character", "age": 25, "pets": ["frog ", "rabbit"]} '*/
// Remember to add parentheses when returning the JSON string from eval. Otherwise, an error is reported. Brackets play the role of force evaluation.
// Otherwise, the JSON string will be treated as a compound statement, and the ("name" :) in it will be treated as a Label, and then the content after parsing will go wrong.
Var obj = eval ('+ Object. toJSON (data) + ')');
Alert (obj. name );

ToQueryString method:
Create a Hash object with the object, call the toQueryString method of the Hash object, and return the call result. The toQueryString method is described in detail when talking about the Hash object.
This method is usually used when Ajax. Request is called. The following is an example:
Copy codeThe Code is as follows:
Object. toQueryString ({action: 'ship ', order_id: 123, fees: ['f1', 'F2'], 'label': 'A demo '})
//-> 'Action = ship & order_id = 123 & fees = f1 & fees = f2 & label = a % 20demo'

ToHTML method:
If the input object parameter is undefined or null, an empty string is returned.
Alert (Object. toHTML ())
Alert (Object. toHTML (null ))
If the object defines the toHTML method, the toHTML method of the object is called. Otherwise, the String static method interpret is called to determine whether the object is null. If it is null, ''is returned '', otherwise, the toString method of the object is called and the call result is returned.
Copy codeThe Code is as follows:
Object. extend (String ,{
Interpret: function (value ){
Return value = null? '': String (value );
},
SpecialChar :{
'\ B': '\ B ',
'\ T':' \ t ',
'\ N':' \ n ',
'\ F':' \ F ',
'\ R':' \ R ',
'\\':'\\\\'
}
});

The following is an example:
Copy codeThe Code is as follows:
Var Bookmark = Class. create ({
Initialize: function (name, url ){
This. name = name;
This. url = url;
},
ToHTML: function (){
Return '<a href = "# {url}" href = "# {url}" >#{ name} </a>'. interpolate (this );
}
});
Var api = new Bookmark ('prototype API ', 'HTTP: // prototypejs.org/api ');
Object. toHTML (api );
//-> '<A href = "http://prototypejs.org/api" href = "http://prototypejs.org/api"> Prototype API </a>'

Keys and values methods:
Let's take a look at the example and I will not go into detail:
Copy codeThe Code is as follows:
Object. keys ()
//-> []
Object. keys ({name: 'prototype', version: 1.5}). sort ()
//-> ['Name', 'version']
Object. values ()
//-> []
Object. values ({name: 'prototype', version: 1.5}). sort ()
//-> [1, 1.5, 'prototype']

Clone method:
'{}' Is the direct volume of empty objects, which is equivalent to new Object ()
Copy codeThe Code is as follows:
Var o = {name: 'prototype', version: 1.5, authors: ['Sam ', 'trigger']};
Var o2 = Object. clone (o );
O2.version = '1. 5 weird ';
O2.authors. pop ();
O. version //-> 1.5
O2.version //-> '1. 5 weird'
O. authors //-> ['same']
// Ouch! Shallow copy !, Note here!

Let's leave the isXXX method empty.

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.