在 IIFE 中使用实例属性
Using instance property in IIFE
如何在方法中使用IIFE中的实例变量?
我的启动方法出现错误:
未捕获的类型错误:未定义不是函数
我在控制台中登录了this.element
,它确实显示为未定义,但在 IIFE 之外它工作正常。
如何让它在 IIFE 内工作?我尝试在 IIFE 中将其作为参数传递,但这也没有用。
function LiveDateTime(element) {
'use strict';
this.element = element;
}
LiveDateTime.prototype = {
setLocale: function (locale) {
this.locale = locale;
},
setOffsetSeconds: function (seconds) {
this.offsetSeconds = seconds;
},
setDaylightSavingTimeSeconds: function (seconds) {
this.daylightSavingTimeSeconds = seconds;
},
start: function () {
(function update() {
var now = new Date();
var now = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds(),
now.getUTCMilliseconds()
);
this.element.innerHTML = now.toLocalString('fr-FR'); // <--
this.timeoutId = setTimeout(update, 50); // <--
})();
},
stop: function () {
clearTimeout(this.timeoutId);
this.timeoutId = 0;
}
};
在变量中存储对this
的引用,如下所示
start: function() {
var self = this;
(function update() {
var now = new Date();
var now = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds(),
now.getUTCMilliseconds()
);
self.element.innerHTML = now.toLocalString('fr-FR'); // <--
self.timeoutId = setTimeout(update, 50); // <--
})();
},
相关文章:
- Backbone.Model.extend不创建实例属性
- 在定义了构造函数之后,是否可以将实例属性添加到JavaScript原型中
- 从原型方法更改实例属性
- 在 IIFE 中使用实例属性
- 在 ES6 中,允许解构类实例属性
- 在 ES6 中自动将参数设置为实例属性
- 将实例属性放置在原型构造函数中,无论好坏
- JS:原型-访问正确的实例属性
- 我可以在Silverlight中的Scriptable Member属性上设置Javascript中的实例属性吗
- 实例属性会模糊原型链吗
- mixin中的prototype.js实例属性
- 为什么不应该't我直接访问实例属性进行写操作
- Javascript”;私人的“;与实例属性相比
- 为什么在原型中声明实例属性而不是在构造函数中声明
- 如何用原型函数更新实例属性,并从另一个函数访问它
- 新的骨干实例属性指向旧的实例属性
- 在实例方法中获取对实例属性的访问权
- ES6类/实例属性
- 为什么赋值影响实例属性而不是原型属性?
- 在Coffee Script中理解类扩展和实例属性