网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

js中this的指向问题归纳的示例分析

这篇文章给大家分享的是有关js中this的指向问题归纳的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

为石峰等地区用户提供了全套网页设计制作服务,及石峰网站建设行业解决方案。主营业务为成都网站设计、网站制作、石峰网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

this

this:上下文,会根据执行环境变化而发生指向的改变.

1.单独的this,指向的是window这个对象

alert(this); // this -> window

2.全局函数中的this

function demo() {
 alert(this); // this -> window
}
demo();

在严格模式下,this是undefined.

function demo() {
 'use strict';
 alert(this); // undefined
}
demo();

3.函数调用的时候,前面加上new关键字

所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象。

function demo() {
 //alert(this); // this -> object
 this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'

4.用call与apply的方式调用函数

function demo() {
 alert(this);
}
demo.call('abc'); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window

5.定时器中的this,指向的是window

setTimeout(function() {
 alert(this); // this -> window ,严格模式 也是指向window
},500)

6.元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素

window.onload = function() {
 let $btn = document.getElementById('btn');
 $btn.onclick = function(){
 alert(this); // this -> 当前触发
 }
}

7.函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素

window.onload = function() {
 let $btn = document.getElementById('btn');
 $btn.addEventListener('click',function() {
 alert(this); // window
 }.bind(window))
}

8.对象中的方法,该方法被哪个对象调用了,那么方法中的this就指向该对象

let name = 'finget'
let obj = {
 name: 'FinGet',
 getName: function() {
 alert(this.name);
 }
}
obj.getName(); // FinGet
---------------------------分割线----------------------------
let fn = obj.getName;
fn(); //finget this -> window

腾讯笔试题

var x = 20;
var a = {
 x: 15,
 fn: function() {
 var x = 30;
 return function() {
  return this.x
 }
 }
}
console.log(a.fn());
console.log((a.fn())());
console.log(a.fn()());
console.log(a.fn()() == (a.fn())());
console.log(a.fn().call(this));
console.log(a.fn().call(a));

答案

1.console.log(a.fn());

对象调用方法,返回了一个方法。

# function() {return this.x}

2.console.log((a.fn())());

a.fn()返回的是一个函数,()()这是自执行表达式。this -> window

# 20

3.console.log(a.fn()());

a.fn()相当于在全局定义了一个函数,然后再自己调用执行。this -> window

# 20

4.console.log(a.fn()() == (a.fn())());

# true

5.console.log(a.fn().call(this));

这段代码在全局环境中执行,this -> window

# 20

6.console.log(a.fn().call(a));

this -> a

# 15

感谢各位的阅读!关于“js中this的指向问题归纳的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


本文名称:js中this的指向问题归纳的示例分析
转载来于:http://bjjierui.cn/article/pichcs.html

其他资讯