可以访问对象的属性,但不能访问函数
Can access an attribute of my object but not a function
我必须弄清楚,如何开发oop-javascript正确的方式。我读了很多关于prototypes
的书,但是互联网向我解释说,我只需要它,如果我创建一个对象很多次。但是我的SuperInterface
只存在一次。所以我创建了一个对象:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: this.superaction
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
执行init()
命令会使title
成功进入控制台。但是警报永远不会被调用。我不明白,为什么不呢?我应该改变什么?
该对象初始化式中间的this
的值是而不是对"正在构建"的对象的引用。在初始化期间没有办法获得这样的引用,因为对象还不存在,您也不会用this
引用它。你不能初始化这样的属性。但是,您可以将其拆分为单独的语句:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: null;
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;
如果调试这段代码,您会发现SuperInterface.actions[0].do_this
是undefined
原因很明显。在评估代码时。
actions: [{
title: 'This is great',
do_this: this.superaction
}]
。这里this
指向窗口对象。
并且在这个窗口对象中不存在superaction .
要使此工作最终完成,您需要
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: null
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;
SuperInterface.init();
我希望你得到了答案。由于 var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: function() {
return SuperInterface.superaction();
}
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
this
在你的例子中指的是数组actions
中的文字对象-它不包含方法superaction
。
相关文章:
- JS可以在Chrome中工作,但不能在Firefox中工作
- WebRTC视频聊天可以在FF中使用,但不能在Chrome中使用
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- 三角库可以与firefox一起使用,但不能在Chrome中使用
- Highcharts可以从服务器加载数据,但不能更新
- 刷新GoogleMaps tile服务器可以使用JavaScript,但不能使用GWT
- node.js可以识别字符模式,但不能识别数字模式
- 如何在元素中处理鼠标事件,但不能在其子元素上处理
- Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- 为什么我可以在javascript中访问asp:TextBox,但不能访问asp:Label
- 扩展了类,但不能访问子类的函数
- IAM允许访问一个dynamoDB方法,但不能访问另一个使用javascript到AWS的方法
- 解析AJAX HTML响应:我可以找到元素,但不能访问它们的innerHTML或值
- Angular Ui-Router |从控制器访问视图中的作用域变量,但不能正常工作
- 为什么我可以访问iFrame,但不能访问它的内容?
- 返回JSON对象,但不能通过$.ajax()访问
- AngularJS的JSON对象可以在视图中访问,但不能在控制器中访问
- 可以访问对象的属性,但不能访问函数
- 在内容脚本中定义的脚本,但不能在弹出(Chrome扩展)访问