JavaScript ?? ??
?? ?? ? ?? ?? ??? ?????.
Javascript ???? 4?? ?? ???? ????.
?? ?? ??
??? ??
??? ??
call() ? Apply()? ?? ?? ??
1. ???? ?? ??
?? ????? ???? ?? ??? ?? ?? ?? ???:
alert("hello");
var result = add(1, 2);
2. ??? ??
//?? ??
function hello(name) {
Alert('hello,' + name);
};
var user = {};
//??? sayHi ??? ???
user.sayHi = hello;
//??? ??
user.sayHi('Zhang San');
???? ?? ??? ??? ?? ? ?? ???: "?? ?? ??" ????? ?? ?? ????(this? ?)? ?? ??(??? ??)??? ???? ??(?? ??)???. "??? ??" ????? ?? ?? ??? ?????. ? ??? ???? ???? ??? ?? ?? ???? ?? ? ?? ?? ??? ? ?? "??? ???"? ?????.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo"></p> <script> function myFunction(a, b) { return a * b; } document.getElementById("demo").innerHTML = myFunction(10, 2); </script> </body> </html>
?? ??? ? ?: ?? ???? ?? ??? ?? ???? this? ???? ????. ?, ?? ??? ???? ??? ? ?? ??? this? ?? ?? ??? ?????. ?? ??? ??? ??? ? this? ?? ?? ??(??? ??)??? ???? ??(?? ??)???. ?? ???? ?? ??? ??? ?????? ?? ????? ?? ??? ???? ??? ?? ??????.
var obj = {
f : function() {
var self = this;
console.log(this == = obj);//true, ?? ?? ??? ?????
???????????????????????????????????????????????????????????????????|
???????????????? console.log(self === obj) ;///true, self? ?? ??? ?? this? ?????.?????????????????????????????????????????????? ?? ????? ???? ?????. };
3. ??? ??
new ???? ???? ??? ???? ???? ?????. ???? ?? ????? ??? ??? ??? ? ????.
var obj = new Object();//Equivalent to
var obj = new Object;
???? ???? ? ??? ????. ? ? ??? ???? ?? ????(this? ?)? ???.
function User(name) {
this.name=name;
Console.debug(this);
}
var user = new User('張三');
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo"></p> <script> function myFunction(arg1, arg2) { this.firstName = arg1; this.lastName = arg2; } var x = new myFunction("John","Doe") document.getElementById("demo").innerHTML = x.firstName; </script> </body> </html>
4.
var name = 'A';
?? (this.name);}
showName();//A, ??? ?? ?????
showName .call(user);//B, ??? ??? ?????
apply()? call()? ????? ???? ?? ?? ????? ?? ???? ????? ??? ????(?? ??). ?? ??? ??? ?? ??? ? ????).