说一说JavaScript中的this
来源:互联网 发布:java用户管理系统建表 编辑:程序博客网 时间:2024/06/06 02:26
情况1:构造函数
function Foo() {
this.name = "qcc";
this.age = "21";
console.log(this); // Foo { name: "qcc", age: 21 }
}
var person = new Foo();
以上代码中,如果函数作为构造函数用,this就代表即将要new出来的对象。
但是如果直接调用Foo()函数,情况如下:
function Foo() {
this.name = "qcc";
this.age = "21";
console.log(this); // Window
}
Foo();
这种情况下this是window。
情况2:函数作为对象的一个属性
var obj = {
x: 10,
fn: function() {
console.log(this); // Object
console.log(this.x); // 10
}
}
obj.fn();
当函数作为一个对象的属性为调用是,this指向该对象。
var obj = {
x: 10,
fn: function() {
console.log(this); // Window
console.log(this.x); // undefined
}
}
var f = obj.fn;
f();
情况3:函数用call或者apply调用
当一个函数被call或者apply调用时,this的值就取传入对象的值。
var obj = {
x: 10,
}
var fn = function() {
console.log(this); // Object
console.log(this.x); // 10
}
fn.call(obj);
情况4:全局&普通函数
全局环境下,this永远是Window。
普通函数在调用时,this也时Window。需要注意下面的情况:
var obj = {
x: 10,
fn: function() {
function f() {
console.log(this); // Window
console.log(this.x); // undefined
}
f();
}
}
obj.fn();
此时的f();也是普通函数。
阅读全文
1 0
- 说一说JavaScript中的this
- 【javascript】javascript中的this
- JavaScript中的this指针
- javascript 中的"this"
- javascript中的this!
- Javascript中的this讲解
- Javascript中的this关键字
- javascript中的this
- JavaScript中的this关键字
- JavaScript中的this详解
- JavaScript中的this指针
- javascript中的this
- JavaScript 中的this 关键字
- 有关javascript中的this
- javascript中的this
- JavaScript 中的 this
- Javascript中的this
- javascript中的this
- HDOJ1061 Rightmost Digit(Java)
- Hamming problem
- more命令与less命令
- SVN 合并的思考:SVN 分支合并主干
- MySQL的行转列、列转行、连接字符串 concat、concat_ws、group_concat函数用法
- 说一说JavaScript中的this
- JMeter-Sampler_BeanShell Sampler
- 摩天楼
- ActiveMQ入门实例
- 使用天平称重,经验证,用四个砝码可以秤出1~40的全部整数重量,请问是哪四个砝码?
- 课程5:神经网络迷你项目-练习6 感知机更新规则
- [Linux] 内核编译安装
- Node.js Events
- UER #2 手机的生产