关于js中的this的指向问题
来源:互联网 发布:硬件温度监控软件 编辑:程序博客网 时间:2024/05/24 06:09
1.全局代码中的 thisalert(this)//window全局范围内的 this 将会指向全局对象,在浏览器中即使 window
2.作为单纯的函数调用 function fooCoder(x) { this.x = x; } fooCoder(2); alert(x);// 全局变量 x值为2 这里 this 指向了全局对象,即 window。在严格模式中,则是 undefined
3.作为对象的方法调用
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
console.log(this.name + ” says ” + sth);
}
}
person.hello(“hello world”);
输出 foocoder says hello world。this 指向 person 对象,即当前对象。
4..作为构造函数
new FooCoder();
函数内部的 this 指向新创建的对象
5.内部函数
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
var sayhello = function(sth) {
console.log(this.name + ” says ” + sth);
};
sayhello(sth);
}
}
person.hello(“hello world”);//clever coder says hello world
在内部函数中,this 没有按预想的绑定到外层函数对象上,而是绑定到了全局对象。这里普
遍被认为是 JavaScript 语言的设计错误,因为没有人想让内部函数中的 this 指向全局对象。
一般的处理方式是将 this 作为变量保存下来,一般约定为 that 或者 self:
var name = “clever coder”;
var person = {
name : “foocoder”,
hello : function(sth){
var that = this;
var sayhello = function(sth) {
console.log(that.name + ” says ” + sth);
};
sayhello(sth);
}
}
person.hello(“hello world”);//foocoder says hello world
- 关于js中的this的指向问题
- js中的this指向问题
- js中的this指向和改变this指向的方法
- js中的this指向问题及解决方案
- 如何理解JS中的this指向问题
- Js中的this指向问题(2)
- JS函数中的this指向问题
- js中的this指向
- JS中的this指向
- JS中的this指向
- js this指向问题
- js this指向问题
- js中关于this的指向
- 关于this指向问题
- 关于this指向问题
- 关于this指向问题
- JS-箭头函数中的this的指向
- js中this关键字的指向问题
- Machine learning for OpenCV 学习笔记 day6
- makefile命令
- 直流电机控制
- SQL实战题目(三)
- 文章标题 实验三:内部模块化的命令行菜单小程序V2.0
- 关于js中的this的指向问题
- Docker下HBase学习,三部曲之三:java开发
- 用C++创建快捷方式
- 全连接神经网络 python实现
- 在CentOS 7.2下升级gcc编译器的版本
- 在CentOS 7.2下升级gcc编译器的版本
- 在CentOS 7.2下升级gcc编译器的版本
- 【Vivado】学习笔记(1)
- java中带有package的java源文件在cmd下得运行