gpt4 book ai didi

javascript - "this._events || (this._events = {});"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:52 25 4
gpt4 key购买 nike

我已经开始学习 Backbone.js。目前我的 JavaScript 技能不太好。我开始检查 backbone.js 文件,发现一行奇怪的代码,我无法弄清楚其用途。代码示例(如果您需要更多上下文,请为开发人员手动下载 backbone.js 并查看第 80 行):

var Events = Backbone.Events = {

// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},

this._events || 是什么意思(this._events = {}); 是什么意思?对我来说,_events 看起来像一个内部变量,但是 (this._events = {}) 用于赋值还是比较?还是 || 在这种情况下是完全不同的操作?

最佳答案

这是一个使用 javascripts“虚假”评估的技巧。它与以下内容相同:

if (this._events) {
// do nothing, this._events is already defined
} else {
this._events = {};
}

var events = this._events[name] || 这行也是如此(this._events[name] = []); 可以翻译成

var events;
if (this._events[name]) {
events = this._events[name];
} else {
this._events[name] = [];
events = this._events[name];
}

关于javascript - "this._events || (this._events = {});"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23212926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com