js中 this 的指向
js中 this的指向一共存在3种地方:
1.全局的this;
2.构造函数的this;
3.call/apply;
一、全局的this:1 function test(){
2 this.d = 3;//函数的默认指向是window
3 var a = 1;
4 function c(){
5 }
6 }
7
8 test(123);
9 console.log(window.d);
10 console.log(this.d);//this 默认指向window
这里有两个点:函数的默认指向是window;全局this 指向 window;
预编译的过程:
ao:
this : window
a
c :function c(){}
go:
test :function test(){}
这里的两个console.log输出的都是3
二、构造函数中this的指向:1 function Test(){
2 this.name = "123";
3 }
4 var test = new
这里的预编译过程是这样的:
GO:Test :function Test(){};
AO:
第一次:this {window};
当new了之后: this : {name:123; __proto__:Test.prototype}
三、call/apply改变this的指向1 //call/apply 改变this指向
2 function Person(){
3 this.name = "张三";
4 this.age = 18
5 }
6 function Programmer(){
7 Person.apply(this);
8 this.work = "Progarmming";
9 }
10
11 var p = new Programmer();
12
根据前面的介绍,可知:Person.apply(this);中this 是指向Programmer的实例化对象, 此处 的this也替换了Person 实例化对象;所以 最后输出就是:
{name: "张三", age: 18, work: "Progarmming"}
1.全局this 指向 window
2.预编译函数 this指向window
3.构造函数的this 指向实例化对象
4.apply/call改变this的指向
补充:js中 this 和 $(this)的区别this是html中返回的类集合([object HTMLImageElement]),而$(this)返回的是Jquery的集合([object Object ])
以下例子是以https://www.miaov.com/网站为页面的一个例子;
1 $(".menu ul").each(function(){
2 var a = $(this);
3 var b = this
4 //test(a.text());
5 debugger
6 test(b.innerText);
7 })
8
9 function test(obj){
10 alert(obj);
11
这里当获取 ul的值,两种方式去取;
我从来不相信什么懒洋洋的自由。我向往的自由是通过勤奋和努力实现的更广阔的人生。 我要做一个自由又自律的人,靠势必实现的决心认真地活着。
版权声明
本文仅代表作者观点,不代表博信信息网立场。