JavaScript笔记——this的取值
来源:互联网 发布:江苏省人工智能学会 编辑:程序博客网 时间:2024/04/30 09:25
有关ECMAScript定义如何获取this请移步ECMAScript中关于如何获取this的定义
绝大多数情况下,函数的调用方式决定了this的取值
全局上下文
console.log(this === window); //true
函数上下文
直接调用
function fn(){ return this;}fn() === window; //true//this的值不是由函数调用设定,默认为全局对象
严格模式下增强了安全措施,this关键字禁止指向全局对象
function fn(){ "use strict"; return this;}fn() === undefined; //truefunction f(){ "use strict"; this.a = 1;}f();// 报错,this未定义var fun = new f();console.log(fun.a); //1
对象方法中的this
指向调用该函数的对象,并且是最靠近的引用
var o = {prop: 37};function independent() { return this.prop;}o.f = independent;o.b = { g: independent, prop: 42};console.log(o.f()); //logs 37console.log(o.b.g()); //logs 42
构造函数中的this
与即将被创建的新对象绑定,可手动设置返回对象
function C(){ this.a = 37;}var o = new C();console.log(o.a); //logs 37function C2(){ this.a = 37; return {a:38};}o = new C2();console.log(o.a); //logs 38
call和apply
this的值被绑定到一个指定的对象上
如果传递的this值不是一个对象,则会使用ToObject操作将其转换为对象
function bar() { console.log(Object.prototype.toString.call(this));}bar.call(7); // [object Number]//会通过new Number(7)转换为对象//如果是字符串则会通过new String('foo')转换为对象
bind
Function.prototype.bind
会创建一个具有相同函数体和作用域的函数,但是新函数的this被永久绑定到bind的第一个参数上,无论这个函数如何被调用
function f(){ return this.a;}var g = f.bind({a:"azerty"});console.log(g()); //azertyvar o = {a:37, f:f, g:g};console.log(o.f(), o.g()); //37, azerty
DOM事件处理函数中的this
事件处理函数中的this指向触发事件的函数
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><button id="btn">button</button><script> function eventHandler() { //this指向#btn console.log(this); //<button id="btn">button</button> } var btn = document.querySelector('#btn'); btn.addEventListener('click', eventHandler, false);</script></body></html>
内联事件处理函数中的this
指向监听器所在DOM元素
<!--<button onclick="console.log(this);"> Show this</button>--><button onclick="alert(this);"> Show this</button><!--window对象,因为没有设置内部函数的this,非严格模式下默认指向全局对象--><button onclick="alert((function(){return this})());"> Show inner this</button>
参考
this - JavaScript | MDN
Javascript 严格模式详解
0 0
- JavaScript笔记——this的取值
- JavaScript笔记整理——this 的工作原理
- javaScript学习笔记——不同的取整函数
- javascript学习笔记——this对象
- JavaScript的this学习笔记
- javascript函数的四种调用模式及参数this的取值
- JavaScript调用模式(this的取值)以及,call(),apply()函数浅析
- 深入javascript——无处不在的this
- Java程序员的JavaScript学习笔记(3——this/call/apply)
- 学习笔记---javascript的this问题
- JavaScript 中 关于 this 的学习笔记
- JavaScript笔记1--this的含义
- javaScript学习笔记——随机数取整
- JavaScript笔记:关于this
- this如何取值?
- 【javascript笔记】this in javascript
- JavaScript学习笔记5-Javascript的this用法
- javascript——this指向
- spring-mvc跳转根目录下的jsp文件
- Permission denied: make_sock: could not bind to address [::]:80
- windows安装composer方法和使用方法
- Centos 6.5 配置连接Windows远程桌面
- 前言
- JavaScript笔记——this的取值
- linux 下 .sh 文件语法
- 1043. Is It a Binary Search Tree (25)-PAT甲级真题
- CountDownLatch的使用
- java常见问题:
- xxx
- 数据结构实验之栈:行编辑器
- 《More Effective C++》阅读记录
- XcodeBoost 插件使用