最近一段时间在学习关于 this 指向的问题, 自己写个随笔, 做个小结
1. this 在普通函数中
- function fn() {
- name: "六月雪",
- console.log(this) // 输出结果为 Windows
- }
- fn();
原因很简单, 函数不被调用, 是不会执行的, Windows 中最大的对象就是 Windows, 直接 fn() 调用函数相当于 Windows.fn(), 所有 this 指向 Windows
2. this 在赋值的函数中
- var fn = function () {
- console.log(this); // 输出结果为 Windows
- }
- fn()
这个不是用等号连接的 fn 吗, 为什么函数里面的 this 不是指向 fn 呢? 其实和上面的是一样的问题, 谁调用指向谁, 虽然把函数赋值给一个变量, 但是, 如果你直接打印 fn 不加括号, 输出的是一整个函数中括号里面的内容, 并没有直接打印 this 的指向, 说明函数在运行的时候还是要调用, 既然是在全局状态下调用, this 的执行当然就是 Windows
3. this 在构造函数中的时候
- function Star(uname) {
- this.uname = uname;
- console.log(this);
- }
- Star(); // 这样其实没有意义, 因为构造函数本身是一个对象模板
- var jsnow = new Star("六月雪");
- console.log(jsnow) //Star {uname: "六月雪"}
输出结果, 指向被实例化的对象
4.this 在构造函数的方法中的时候, this 的指向
- function Star(uname) {
- this.uname = uname;
- this.sing = function () {
- console.log(this); // 输出结果 Star {uname: "六月雪", sing: ƒ}
- }
- }
- var jsnow = new Star("六月雪");
- jsnow.sing()
构造函数中的 this 指向, 依旧是被实例化的对象
5. 在 prototype 外挂方法的时候
- function Fn(uname) {
- this.uname = uname;
- }
- Fn.prototype.sing = function () {
- console.log(this); // 输出 Fn {uname: "六月雪"}
- }
- var jsnow = new Fn("六月雪")
- jsnow.sing()
this 指向被实例化的对象
6. 当使用 prototype 的方法外挂对个对象的时候
- function Fn(uname) {
- this.uname = uname;
- }
- Fn.prototype = {
- sing: function () {
- console.log(this);
- },
- dance: function () {
- console.log("just so so")
- }
- }
- var jsnow = new Fn("六月雪")
- jsnow.sing() // 输出依旧是被实例化的对象
- jsnow.dance()
7. 当函数中带有返回值且返回值是简单数据类型的时候
- var Fn = function () {
- this.age = 18;
- return 1;
- }
- var jsnow = new Fn();
- console.log(jsnow.age); // 输出 18
这里身边的大神解释说, 返回值为简单数据类型的时候, 有和没有其实 没有任何区别, 并不影响输出结果
8. 当返回值为复杂数据类型的时候 (我是学习阶段), 那 function 距离
- var Fn = function () {
- this.age = 18;
- return null;
- }
- var jsnow = new Fn();
- console.log(jsnow.age); //18
返回值居然又成了 18...(特殊记忆一下呗)
至于为什么, 我也解释不了, 可能是因为 null 是一个特殊的对象吧, 说实话, 我很迷惑为什么 null 设计的时候会是一个对象, 当然有些东西当做结论记住就行了, 不用去追求为什么; 不然, 我还想问为什么中国人要用英文写代码了
当返回值为复杂数据类型的时候, 返回值为 underfind 的时候, 就说明 this 的指向已经发生了改变, 不再指向被实例化的对象, 而是返回的复杂数据类型
**********
当然, 说到对象, 不得不想到了一个特殊的对象, null, 打印 typeof 的时候, null 的返回值居然是对象
console.log(typeof null) //object
然后用 null 当对象返回试试
来源: http://www.bubuko.com/infodetail-3346955.html