我的前端学习笔记 js关于this的指向
来源:互联网 发布:应用程序与网络端口 编辑:程序博客网 时间:2024/06/11 04:56
原文链接:http://blog.163.com/thinker_creator/blog/static/1019331492009101545251234/
1. 方法调用模式
当一个函数被保存为对象的一个属性时, 我们称它为一个方法, 当一个方法被调用时, this指向该对象, 如:
var obj = {
value: 1,
getValue: function() {
alert(this.value);
}
};
obj.getValue(); // 输出1, 此时的this指向obj
注意: 该模式中, this到对象的绑定发生在方法被调用的时候.
2. 函数调用模式
当一个函数并非一个对象的属性时, 它被当作一个函数来调用, 此时的this指向全局对象(window), 如:
window.value = 1;
function getValue() { alert(this.value); }
getValue(); // 输出1, 此时的this指向window.
3. 构造器调用模式
结合new前缀调用的函数被称为构造器函数, 此时的this指向该构造器函数的实例对象, 如:
function show(val) {
this.value = val;
};
show.prototype.getVal = function() {
alert(this.value);
};
var func = new show(1);
func.getVal(); // 输出1
alert(func.value) // 输出1
// 从上面的结果, 可以看出, 此时的this指向了func对象.
4. apply/call调用模式
apply和call方法可以让我们设定调用者中的this指向谁, 如:
var fun = function(str) {
this.status = str;
}
fun.prototype.getStatus = function() {
alert(this.status);
}
var obj = {
status: "loading"
};
fun.prototype.getStatus.apply(obj); // 输出"loading", 此时getStatus方法中的this指向了obj
0 0
- 我的前端学习笔记 js关于this的指向
- 我的前端学习笔记 关于js数据类型
- js中关于this的指向
- 关于js中的this的指向问题
- JS this的指向
- js的this指向
- 了解学习JS中this的指向
- 关于this的指向
- 关于this的指向
- JS:this关键字的指向
- js中this的指向
- js中this的指向
- js中this的指向
- js this的指向详解
- js中this的指向
- js中 this 的指向
- js中this的指向
- js中this的指向
- 快速排序算法真神奇
- 进入新市场时要避免犯下的三个错误
- Huffman树
- Leetcode35: Roman to Integer
- TCP和Http的区别!我都搞懂了,你就别迷糊了!
- 我的前端学习笔记 js关于this的指向
- 解决 Your project contains error(s),please fix them before running your application问题 貌似好多人都有遇到这问题,而且网
- C#高级编程第十天----C#预处理器
- OC-数组
- json解析
- Array Pascal's Triangle
- CISC 与 RISC
- PHP5中Cookie与 Session详解
- HDOJ 2031 进制转换