This article mainly introduces the implementation of objects in JavaScript and Promise objects. For more information, see all objects in JavaScript: strings, values, arrays, and functions. The following small series will collect and organize the implementation of javascript objects and promise objects. The details are as follows:
Objects everywhere
Window object
Common attributes and Methods
Location
Contains the URL of the page. If this attribute is changed, the browser accesses the new URL.
Status
Contains a string that will be displayed in the browser status. Usually in the lower left corner of the browser
Onload:
Contains the functions to be called after the page is fully loaded.
Document:
Contain DOM
Alert method:
Show a reminder
Prompt method:
Similar to alert, but the information will be obtained from the user
Open
Open a new window
Close
Close Window
SetTimeout:
Call a processing function after the specified interval
Setlnterval
Calls a processing function repeatedly at a specified interval.
Window. onload
By specifying a function to the onload attribute of window, you can ensure that the Code is not run before the page load and DOM are fully established.
Function used to change the DOM
Window. onload = function () {// code here} // function is an anonymous function assigned to onload
The reason we don't talk about window. inload = init () is that we use its value instead of calling a function.
Assign the value of a function to the inload attribute of the window object so that it can be executed after the page is loaded.
There are two ways to create the window. onload handler: Use the function name and use the anonymous function.
The two methods basically do the same thing, but if the function assigned to window. onload is used elsewhere, use the function name.
Document Object
Common attributes and Methods
Domain:
The domain of the server that provides the documentation, such as kelion.com.
Title:
You can obtain the document title through document. title.
URL:
Document URL
GetElementById method:
Obtain this element based on the element id.
GetElementsByTagName,
GetElementsByClassName:
These two methods are similar to the previous one, except that they use tags and classes to obtain elements.
CreateElement:
Create new elements suitable for inclusion in the DOM
CreateElement
// Create
Element, var li = document. createElement ("li"); // assign li. innerHTML = "songName" to the newly created element; // obtain
Element var ul = document. getElementById ("playlist ") //
- Add the element to ul. appendChild (li)
Note: Before 8th lines of code are executed, the li element is always independent of the DOM.
Element Object
Common attributes and methods:
InnerHTML:
Content containing elements
ChildElementCount:
Number of elements saved
FirstChild
First child element
AppendChild method:
InsertBefore method:
Used to insert an element as a child element of an element.
GetAttribute Method
SetAttribute Method
You can set and obtain attributes in an element in two ways: "src", "id", and "class ".
Finally, let's take a look at the button object.
The button object has a frequently used attribute:
Onclick (used to monitor whether a button is pressed ).
Var button = document. getElementById ("Button"); // The button is only a variable name, which can be button1, button2, and so on. However, it is essentially a button.
Button. onclick = handleButtonClick;
Ps: Implementation of Promise objects in Javascript
Many front-end friends should have heard of Promise (or Deferred) objects. Today I will talk about my understanding of Promise.
What?
Promise is one of the specifications of CommonJS. It has resolve, reject, done, fail, then and other methods to help us control the code flow and avoid multi-layer nesting of functions. Nowadays, Asynchronization is becoming more and more important in web development. for developers, this kind of non-linear execution programming makes developers feel difficult to control, and Promise allows us to better control the code execution process, jQuery and other popular js libraries have implemented this object. ES6, which will be released at the end of the year, will also implement Promise native.
Why
Imagine a scenario where two asynchronous requests and the second request must use the data of the first request, then the code can be written in this way.
ajax({ url: url1, success: function(data) { ajax({ url: url2, data: data, success: function() { } }); } });
If you continue to perform the next operation in the callback function, the number of nested layers will increase. We can make appropriate improvements to write the callback function out.
function A() { ajax({ url: url1, success: function(data) { B(data); } }); } function B(data) { ajax({ url: url2, success: function(data) { ...... } }); }
Even if the code is rewritten like this, the Code is not intuitive enough, but with the Promise object, the code can be clearly written and clearly displayed. Please refer
New Promise (A). done (B );
In this way, function B does not need to be written in the callback of function.
How
The current ES standard does not support Promise objects, so let's do it ourselves. The general idea is that two arrays (doneList and failList) are used to store the callback function queue when the operation is successful and the callback queue when the operation fails.
* State: the current execution status, including pending, resolved, and rejected3.
* Done: Add a successful callback function to doneList.
* Fail: Add a failed callback function to failList.
* Then: add the callback function to doneList and failList respectively.
* Always: Add a callback function that will be called whether successful or failed.
* Resolve: changes the status to resolved and triggers all successfully bound callback functions.
* Reject: changes the status to rejected and triggers all failed callback functions for binding.
* When: the parameter is an asynchronous or delayed function, and the return value is a Promise cash. when all functions are successfully executed, the resolve Method of the object is executed. Otherwise, the reject method of the object is executed.
The following is my implementation process:
var Promise = function() { this.doneList = []; this.failList = []; this.state = 'pending';};Promise.prototype = { constructor: 'Promise', resolve: function() { this.state = 'resolved'; var list = this.doneList; for(var i = 0, len = list.length; i < len; i++) { list[0].call(this); list.shift(); } }, reject: function() { this.state = 'rejected'; var list = this.failList; for(var i = 0, len = list.length; i < len; i++){ list[0].call(this); list.shift(); } }, done: function(func) { if(typeof func === 'function') { this.doneList.push(func); } return this; }, fail: function(func) { if(typeof func === 'function') { this.failList.push(func); } return this; }, then: function(doneFn, failFn) { this.done(doneFn).fail(failFn); return this; }, always: function(fn) { this.done(fn).fail(fn); return this; }};function when() { var p = new Promise(); var success = true; var len = arguments.length; for(var i = 0; i < len; i++) { if(!(arguments[i] instanceof Promise)) { return false; } else { arguments[i].always(function() { if(this.state != 'resolved'){ success = false; } len--; if(len == 0) { success ? p.resolve() : p.reject(); } }); } } return p;}Improve
Currently, only the basic functions of Promise are implemented, but there are still some situations that cannot be processed. For example, to implement the serialization of three or more asynchronous requests, currently, my Promise cannot support new Promise (). then (B ). in the form of then (C), jQuery implements the pipe function for the Deferred (Promise) object in version 1.7. You can use this function to implement the above functions. The code is $. deferred (). pipe (B ). then (C), I tried to read the code of jQuery but failed to understand it. I hope some great gods can give some implementation ideas.