// 声明一个变量
var StateJS;
// 使用 function 声明一个方法,并立即调用。这样的目的是创建一个私有作用域,里面的变量不会泄露到全局空间
(function (StateJS) {
var Behavior = (function () {
// 定义构造函数
function Behavior(behavior) {
this.actions = [];
if (behavior) {
this.push(behavior); // NOTE: this ensures a copy of the array is made
}
}
// 定义成员方法
Behavior.prototype.push = function (behavior) {
Array.prototype.push.apply(this.actions, behavior instanceof Behavior ? behavior.actions : arguments);
return this;
};
/**
* Tests the Behavior instance to see if any actions have been defined.
* @method hasActions
* @returns {boolean} True if there are actions defined within this Behavior instance.
*/
Behavior.prototype.hasActions = function () {
return this.actions.length !== 0;
};
Behavior.prototype.invoke = function (message, instance, history) {
if (history === void 0) { history = false; }
this.actions.forEach(function (action) { return action(message, instance, history); });
};
// 返回构造函数,于是上面的 var Behavior = 构造函数
return Behavior;
})();
// 将构造函数定义到 StateJS
StateJS.Behavior = Behavior;
// 如果之前已经有 StateJS,则使用之前的,否则将 StateJS 赋值为一个新对象{},并且传入
})(StateJS || (StateJS = {}));
在网上看到上面这段代码,上面的定义构造函数为什么可以写成下面这种形式,之前从没见过这种写法,谁能解释下。
function Behavior(behavior) {
this.actions = [];
if (behavior) {
this.push(behavior); // NOTE: this ensures a copy of the array is made
}
}### 问题描述
问题出现的环境背景及自己尝试过哪些方法
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
这是ES5写法,用一个function来实现构造器函数