Rails默认安装的cable.js中this指向及顶层this警告的优化方案咨询
Rails Cable.js中的
this指向问题及改进方案 首先,先明确原代码里的this到底是什么:
你贴的这段是一个立即执行函数表达式(IIFE),末尾的.call(this)会把IIFE内部的this绑定到外部的this上。在标准浏览器环境下,这个外部的this就是全局的window对象——也就是警告里说的“顶层this”。这段代码的作用是把App对象挂载到全局作用域,让Action Cable能通过全局的App.cable访问。
之所以会收到警告,是因为直接依赖顶层this会带来两个问题:
- 代码意图不清晰,别人看的时候得推断
this的指向 - 在严格模式或者非浏览器环境下,
this可能会变成undefined,导致代码报错
最简单直接的改进方法
直接把代码里的this替换成明确的window对象,这样既消除了歧义,又能保持原有的功能:
// Action Cable provides the framework to deal with WebSockets in Rails. // You can generate new channels where WebSocket features live using the // `rails generate channel` command. // // = require action_cable // = require_self // = require_tree ./channels (function() { window.App || (window.App = {}); window.App.cable = ActionCable.createConsumer(); })();
更规范的写法(推荐)
如果想让代码更严谨,可以加上严格模式,同时把逻辑拆得更清晰:
// Action Cable provides the framework to deal with WebSockets in Rails. // You can generate new channels where WebSocket features live using the // `rails generate channel` command. // // = require action_cable // = require_self // = require_tree ./channels (function() { 'use strict'; // 确保App对象存在,不存在就初始化 window.App = window.App || {}; // 创建Action Cable消费者 window.App.cable = ActionCable.createConsumer(); })();
这样写的好处:
- 完全避免了对顶层
this的依赖,代码意图一目了然 - 严格模式能帮你提前发现一些潜在的语法问题
- 拆分后的代码可读性更高,后续维护也更方便
内容的提问来源于stack exchange,提问作者CodeFinity
相关产品推荐
相关产品推荐

