Home Web Front-end JS Tutorial Prototype Object object learning_prototype

Prototype Object object learning_prototype

May 16, 2016 pm 06:50 PM

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.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles