javascript小知识1 this的用法

时间:2021-01-22 21:40:55

函数的应用:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function f(){
alert(this.x);
}
var x = 1;
var a = {
x :2
}
a.f2 = f;
var cc = a.f2()
console.log(cc)
</script>
</body>
</html>

你猜 cc 是多少,是2;

再看一个例子:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script> var x = 1;
var a = {
x: 2,
fn: function() {
return (this.x)
}
}
var b = {
x: 3
}
q = a.fn();
p = a.fn;
q1 = p();
b.f2 = a.fn;
q3 = b.f2();
q5 = (b.f2)();
d = b.f2;
q4 = d();
console.log("q" + "~~~~" + q)
console.log("q1" + "~~~~" + q1)
console.log("q3" + "~~~~" + q3)
console.log("q4" + "~~~~" + q4)
console.log("q5" + "~~~~" + q5)
</script>
</body>
</html>

注意q3与q5这俩结果是一样的;