Home > Web Front-end > JS Tutorial > body text

Prototype Object object learning_prototype

WBOY
Release: 2016-05-16 18:50:02
Original
860 people have browsed it

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.”).
My personal understanding of the namespace mentioned above is equivalent to C# The static class in , which means providing tool functions, should not be the same concept as the namespace in C#. Because the namespace in C# is not directly followed by a method, it must be an object and then call the method, but it is somewhat similar to the namespace in C
clone
extend
inspect
isArray
isElement
isFunction
isHash
isNumber
isString
isUndefined
keys
toHTML
toJSON
toQueryString
values ​​

Copy code The code is as follows:

//Create Object object by anonymous function call
(function() {

//Get the string expression of the type, (Prototype learning - tool function learning ($ method)) There are detailed instructions in this log
function getClass(object) {
return Object.prototype.toString.call(object)
.match(/^[objects(.*)]$/)[1];
}

//Inherited method, very simple The class copying mechanism is to copy all the properties and methods in the source to the destination. If it is a reference type, the source and destination will point to the same address
function extend(destination, source) {
for ( var property in source)
destination[property] = source[property];
return destination;
}

//Return the string expression of 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 of object (JavaScript Object Notation)
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 query string, for example: param1=value1¶m2=value2
function toQueryString(object) {
return $H(object).toQueryString();
}

//Return HTML string
function toHTML(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
}

//Get all keys of object
function keys(object) {
var results = [];
for (var property in object)
results.push(property);
return results;
}

//Get all values ​​of object
function values(object) {
var results = [];
for (var property in object)
results.push(object[property]);
return results;
}

//Copy all properties and methods in 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);
}

//Judge whether object is an array
function isArray(object) {
return getClass(object) === "Array";
}

//Judge whether object is Prototype Hash object
function isHash(object) {
return object instanceof Hash;
}

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

//Determine whether object is a string
function isString(object) {
return getClass(object) === "String";
}

//Determine whether object is a number
function isNumber(object) {
return getClass(object) === "Number";
}

//Determine whether object has been defined
function isUndefined(object) {
return typeof object === "undefined";
}

//Return Object 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 code The 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 calling process var value = toJSON(object[property]); and finally returns a JSON format String representation, let’s take a look at the example:
Copy code The code is as follows:

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
/* '{"name": "Violet", "occupation": " character", "age": 25, "pets": ["frog","rabbit"]}' */
//Remember to add parentheses when eval returns the JSON string, otherwise an error will be reported, here Parentheses serve to force evaluation.
//Otherwise, the JSON string will be regarded as a compound statement, and the ("name":) inside will be regarded as a Label, and then an error will occur when parsing the following content
var obj=eval('(' Object.toJSON (data) ')');
alert(obj.name);

toQueryString method:
Create a Hash object with object, and then call the Hash object toQueryString method, and returns the call result. When talking about Hash objects, the toQueryString method will be discussed in detail.
Generally this method is often used when calling Ajax.Request. Let’s take a look at an example:
Copy code The 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 demo'

toHTML method:
If the object parameter passed in is undefined or null Will return an empty string
alert(Object.toHTML())
alert(Object.toHTML(null))
If object defines the toHTML method, call the toHTML method of object, otherwise call String's The static method interpret actually judges whether the object is null. If it is null, it returns ''. Otherwise, it calls the toString method of the object and returns the call result
Copy code The 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',
'\': '\\'
}
});

Look at the example below:
Copy the code The code is as follows:

var Bookmark = Class.create({
initialize: function(name, url) {
this.name = name;
this.url = url;
},
toHTML : function() {
return '#{name}'.interpolate(this);
}
});
var api = new Bookmark('Prototype API', 'http://prototypejs.org/api');
Object.toHTML(api);
//- > 'Prototype API'

keys and values ​​methods:
You will understand it after looking at the example, so I won’t go into details:
Copy code The 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.5, 'Prototype']

clone method:
'{} ' is the direct quantity of the empty object, equivalent to new Object()
Copy code The code is as follows:

var o = { name: 'Prototype', version: 1.5, authors: ['sam', 'contributors'] };
var o2 = Object.clone(o);
o2.version = ' 1.5 weird';
o2.authors.pop();
o.version // -> 1.5
o2.version // -> '1.5 weird'
o.authors // -> ['sam']
// Ouch! Shallow copy!, pay attention here!

I won’t talk about the isXXX method.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!