What is this?

JavaScript中this的复杂用法
本文深入探讨了JavaScript中this关键字的含义及其在不同场景下的应用,包括其在类基语言中的简单用法,在函数内的多变含义,以及在事件处理器中的具体表现。

(This is an article I wrote several years ago to explain the this keyword in some programming languages. The title is a pun intended.)

Java, C# etc.

The this is a keyword in programming languages such as Java, C# and JavaScript. In the former two class based languages, the value of this is straightforward and simple. It means the current object instantiated with the class definition which contains this. In these languages, this can only be used in a statement within a function i.e. a method of its containing class. It cannot be used in the right side of an initialization statement belonging to the declaration part of the class. A special case is that like other non-static variables this cannot be used in a static method as it doesn't need any instance to be called. Put simply, this only appears in one kind of place and there is only one way in which the containing code is called and thus has just one meaning.

Outside Functions In JavaScript

Now comes our focus --JavaScript. In this prototype based language with great simplicity and ingenuity, the value of this is a little complicated. It can be used outside or inside a function, and can mean different things in either situation.

As its name implies, JavaScript is a script language. That means it usually shows in the form of snippets embedded in a host (a browser in our discussion)instead of a standalone application. A script snippet consists of statements and functions. This is the current object or context object in the current scope. When this stands in an top level statement outside of any function, it refers to the global object -- the current window object. (Examples used below runs in a Firefox equipped with Firebug)

//Example 1
//A log function to work around the duplicated string issue in the js console
function log(msg){
    if (console)
    {
        console.log(new Date().getTimeString()+' >> '+msg);
    }
}
//get a string form of a Date object
Date.prototype.getTimeString=function() {
    if (!(this instanceof Date))    return;
    var d=":";
    var result=this.getHours()+d+this.getMinutes()+d+this.getSeconds()+d+this.getMilliseconds();
    return result;
}

this.abc = "hello";
log(this); //10:28:4:281 >> [object Window]
log(window.abc); //10:28:4:283 >> hello
log('this is the window? ' + (this==window));  //10:28:4:283 >> this is the window? true

Inside Functions In JavaScript

When this appears in a function, it becomes more interesting. A function in JavaScript is not necessarily bound to a object. Instead a function could be stuck to an object instance or a constructor's prototype object manually or declared as a method in an object literal. Consequently a function can be called either directly or as an object's method. Besides, every function can act as an object constructor. In all these circumstances this means differently and we cannot be sure about its meaning when the container function is defined until it is called. Below are some examples.
//Example 2
//This might be the most familiar form we meet this where its container function acts as a constructor
function  father(){
this.age=45;
this.howOld=function(){
console.log('I am '+this.age+' years old.');
}
}
var f=new father();
f.howOld();  //prints 'I am 45 years old'

//Example 3
//even a nested function is not bound to the object created with the outer function
function father(){
this.showMe=function(){
inner();
console.log(this);//prints 'Object'
}
function inner(){
console.log(this);  //prints 'Window'
}
}
var f=new father();
f.showMe();

//Example 4
//A function is called first as an object's method then directly
var career='teacher';
function whoAmI(){
console.log('I am a '+this.career);
}
function father(){
this.career='driver';
}
father.prototype.whoAmI=whoAmI;
var f=new father();
f.whoAmI();  //prints 'I am a driver'
whoAmI();  //prints 'I am a teacher'

//Example 5
//changes the above example a little
var career='teacher';
function father(){
this.career='driver';
}
father.prototype.whoAmI=function(){
console.log('I am a '+this.career);
}
var f=new father();
f.whoAmI();  //prints 'I am a driver'
var w=f.whoAmI;
w();  //prints 'I am a teacher'

Now let's show the underlying reason for the diverse meaning of this in JavaScript. Fortunately it's rather simple. This refers to the context object. According to the form in which a function is called, an object may be passed to it explicitly or implicitly. If no object is passed, as we call a function directly, this points to the global object -- window, just like what happens in a top level statement.If an object is passed to the called function, there are two manners.

1. instance.method(parameters)
The object instance is passed to the function as the value of this implicitly. We can imagine it in a 'static method' way: object_method(instance, other_parameters). Using instance.method([parameter])makes calling function easier and briefer.
2. function object_constructor(parameters){functionbody}
var instance=new object_constructor(parameters);
An new anonymous empty object is passed to the constructor function as the value of this implicitly. Then we can add properties and methods to it.

Inside Event Handlers In JavaScript

One common usage of functions of JavaScript is to register them as event handlers. In such a function, this refers to the object that fires the event.

//Example 6
//In the function registered as the click event listener of a button, alert the Id of the event publisher via this.
document.getElementById("btnShowMe").addEventListener("click", function() {alert("My Id is " + this.id);}, false); //My id is btnShowMe
### Understanding HTTP: What is HTTP and How Does It Work HTTP (HyperText Transfer Protocol) is the foundation of data communication on the World Wide Web. It is an application-layer protocol used to transfer data between a client (such as a web browser) and a server over the internet. HTTP defines how messages are formatted and transmitted, and it specifies the actions that web servers and browsers should take in response to various commands [^1]. At its core, HTTP operates as a request-response protocol. A client, such as a web browser, sends an HTTP request to a server. The server then processes the request and returns an HTTP response. This exchange typically involves the retrieval of web resources such as HTML documents, images, and other files . #### HTTP Request Methods HTTP supports several request methods, each serving a specific purpose. The most commonly used methods include: - **GET**: Retrieves data from the server. This is the most common method used to fetch web pages. - **POST**: Submits data to be processed to the server. It is often used in forms where users input data. - **PUT**: Replaces the current representation of a resource with the request payload. - **DELETE**: Deletes the specified resource. - **PATCH**: Applies partial modifications to a resource. Each request includes a request line, headers, and optionally a message body. The request line contains the method, the path to the resource, and the HTTP version. Headers provide additional information about the request or response, such as content type and length [^1]. #### HTTP Status Codes HTTP status codes are three-digit numbers returned by the server to indicate the outcome of the request. Some common status codes include: - **200 OK**: The request was successful. - **301 Moved Permanently**: The requested resource has been permanently moved to a new location. - **400 Bad Request**: The server could not understand the request due to invalid syntax. - **401 Unauthorized**: Authentication is required to access the resource. - **403 Forbidden**: The server understood the request but refuses to fulfill it. - **404 Not Found**: The requested resource could not be found. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. #### How HTTP Works: A Simple Example When a user types a URL into a browser, the browser sends an HTTP request to the server hosting the website. The server processes the request and sends back an HTTP response, which includes the requested resource (such as a web page) along with the appropriate status code. For example, if a user requests the homepage of a website, the browser might send a GET request like this: ``` GET / HTTP/1.1 Host: www.example.com ``` The server responds with an HTTP response like this: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1234 <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body> <h1>Welcome to Example Website</h1> </body> </html> ``` The browser then renders the HTML content and displays it to the user . #### HTTP vs. HTTPS HTTP is inherently insecure because data is transmitted in plain text, making it vulnerable to interception. HTTPS (HyperText Transfer Protocol Secure) addresses this issue by encrypting the data using SSL/TLS protocols. This ensures that the data remains private and secure during transmission . #### HTTP Versions Over the years, HTTP has evolved to improve performance and efficiency. The main versions include: - **HTTP/1.0**: The original version, which opened a new TCP connection for each request-response cycle. This led to latency issues. - **HTTP/1.1**: Introduced persistent connections, allowing multiple requests and responses to be sent over a single connection. This significantly improved performance . - **HTTP/2**: Built on the SPDY protocol, HTTP/2 introduced features such as multiplexing, header compression, and server push to further enhance performance [^1]. - **HTTP/3**: The latest version, which uses the QUIC protocol instead of TCP to reduce latency and improve connection reliability . #### Conclusion HTTP is a critical protocol that enables the seamless exchange of data on the web. Understanding its fundamentals helps in building efficient web applications and troubleshooting issues related to data transmission. ```python # Example of sending an HTTP GET request using Python&#39;s requests library import requests response = requests.get(&#39;https://www.example.com&#39;) print(f"Status Code: {response.status_code}") print(f"Response Body: {response.text}") ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值