Javascript 是否有可能保护';这';引用绑定对象中的函数?
给出以下JavaScript(相关HTML将发布在问题的底部): 我们可以使用以下方法从对象外部调用Javascript 是否有可能保护';这';引用绑定对象中的函数?,javascript,Javascript,给出以下JavaScript(相关HTML将发布在问题的底部): 我们可以使用以下方法从对象外部调用quote()函数: document.getElementById('load').addEventListener('click', app.quote.bind(app)); 或者直接调用函数(不绑定为对事件处理程序的回调): 但是,我尝试在对象本身内创建事件处理程序,使用: 'clickhandler': function(){ this.trigger.addEventLi
quote()
函数:
document.getElementById('load').addEventListener('click', app.quote.bind(app));
或者直接调用函数(不绑定为对事件处理程序的回调):
但是,我尝试在对象本身内创建事件处理程序,使用:
'clickhandler': function(){
this.trigger.addEventListener('click', this.quote);
}
当然,这失败了(正如预期的那样,因为这里是(使用IIFE))
我意识到,这个
将在创建对象时/在初始化之前引用窗口
对象,但是有没有一种方法我看不到在对象本身中创建和触发事件处理
我意识到我想象中的互联网点有很大一部分是专门来自JavaScript的,但学习它会意外地导致完全混乱和不足的时刻;这不是为了原谅我的无知,而是为了解释它
最后,HTML(例如它是):
切换消息
顺便说一句,我看了以下链接/建议问题:
为清楚起见,我尝试创建对象本身,并在对象内创建和分配事件处理,而不必事后调用其方法。这就是我被卡住的地方(我怀疑这是不可能的)
- -我看不出相关性(尽管也许我只是在这一点上感到疲劳)
- -这表明唯一可行的方法是在初始化后通过添加新方法扩展
对象,该方法可行,但与我想做的相反(我意识到生活是不公平的,但即便如此……)应用程序
- -处理事件处理程序,但似乎不直接适用。不过我可能是误解了
var App = function App(){
this.clickhandler()
}
App.prototype =
{
'messages': [{
'author': 'Maya Angelou',
'quote': "If you don't like something, change it. If you can't change it, change your attitude."
}, {
'author': 'Richard Feynman',
'quote': "Hell, if I could explain it to the average person, it wouldn't have been worth the Nobel prize."
}, {
'author': 'Eddie Izzard',
'quote': "Cats have a scam going – you buy the food, they eat the food, they fuck off; that's the deal."
}, {
'author': 'George Carlin',
'quote': "I would never want to be a member of a group whose symbol was a man nailed to two pieces of wood. Especially if it's me!"
}],
'textProp': 'textContent' in document.body ? 'textContent' : 'innerText',
'outputTo': document.querySelector('#output'),
'trigger': document.querySelector('#load'),
'quote': function () {
console.log('hey')
var n = Math.floor(Math.random() * this.messages.length),
f = document.createElement('figure'),
c = document.createElement('figcaption'),
frag = document.createDocumentFragment();
f[this.textProp] = this.messages[n].quote;
c[this.textProp] = this.messages[n].author;
frag.appendChild(f);
frag.appendChild(c);
this.outputTo.innerHTML = '';
this.outputTo.appendChild(frag);
},
'clickhandler' : function(){
this.trigger.addEventListener('click', this.quote.bind(this));
}
};
//just create an object
app = new App();
此变量仅引用应用程序。所以只需使用应用程序
var app = {
someVar: 'thing',
someMethod: function(){
alert(app.someVar);
}
};
或者你可以
function createApp(){
var app = {};
app.someVar = 'thing';
app.someMethod = function(){
alert(app.someVar);
};
return app;
}
在某个时候,您需要将
.bind()
方法绑定到应用程序中(除非您无处不在)。但是,这不一定在传递app.quote
方法的位置(例如,绑定为事件侦听器),但可能直接在app
对象声明之后:
var app = {
…,
quote: function() {
… this …
}
};
app.quote = app.quote.bind(app);
如果周围有下划线,则可以使用以下选项:
var app = _.bindAll({
…,
quote: function() {
… this …
}
}, "quote");
如果您是-它可以是构造函数、IEFE,无论什么-您可以.bind()
直接在函数声明的位置执行函数:
function App() {
…
this.quote = function() {
… this …
}.bind(this);
}
使用coffeescript或ES6,您还可以使用fat arrow函数语法作为实现此目的的工具。您可以执行以下操作,而不是使用object literal:
var app = new function () {
this.messages = [{
'author': 'Maya Angelou',
'quote': "If you don't like something, change it. If you can't change it, change your attitude."
}, {
'author': 'Richard Feynman',
'quote': "Hell, if I could explain it to the average person, it wouldn't have been worth the Nobel prize."
}, {
'author': 'Eddie Izzard',
'quote': "Cats have a scam going – you buy the food, they eat the food, they fuck off; that's the deal."
}, {
'author': 'George Carlin',
'quote': "I would never want to be a member of a group whose symbol was a man nailed to two pieces of wood. Especially if it's me!"
}];
this.textProp = 'textContent' in document.body ? 'textContent' : 'innerText';
this.outputTo = document.querySelector('#output');
this.trigger = document.querySelector('#load');
this.quote = function () {
var n = Math.floor(Math.random() * this.messages.length),
f = document.createElement('figure'),
c = document.createElement('figcaption'),
frag = document.createDocumentFragment();
f[this.textProp] = this.messages[n].quote;
c[this.textProp] = this.messages[n].author;
frag.appendChild(f);
frag.appendChild(c);
this.outputTo.innerHTML = '';
this.outputTo.appendChild(frag);
};
this.trigger.addEventListener('click', this.quote.bind(this));
};
一个小小的变化。在初始化对象的属性之前声明对象可能有助于您的用例
var app = {};
app["messages"] = "test message";
app["textProp'] = 'textContent' in document.body ? 'textContent' : 'innerText';
app['quote']= function () {
var n = Math.floor(Math.random() * this.messages.length),
f = document.createElement('figure'),
c = document.createElement('figcaption'),
frag = document.createDocumentFragment();
f[app.textProp] = app.messages[n].quote;
}
this.trigger.addEventListener('click',this.quote.bind(this))代码>此
所指的内容取决于如何调用clickhandler
。如果您将其称为“正常”,如app.clickhandler()
,此
指的是app
,您应该按照epascarello的建议使用.bind
。看见您的问题与使用对象文字无关。@epascarello:我试图做的(我的问题可能不够清楚,对此我深表歉意)是将事件处理程序绑定到对象本身,以便不必调用函数。本质上是只创建对象并分配处理,而不调用对象或其方法。不,这不起作用。对象文字仅由key:value
对组成,其中value
可以是任何表达式。但是这些表达式无法访问对象本身,因为它还不存在。简言之,在初始化过程中,您不能引用对象本身。您有一个使用逗号运算符的长表达式,而不是使用多个表达式语句的原因吗?@FelixKling No,应该是代码>,我只是从op的小提琴上复制了代码,但忘了更改:)@Bergi虽然构造函数可能会以这种方式泄漏,但这是在你的控制之下,对吗?除非您使用app.constructor
,否则应该没有问题。我不太关心“失去控制”,而是更关心内存消耗。存在两个完全超豪华的物体,可以很容易地避免。例如,省略new
,让函数以返回此;}结束。调用({})
。
function App() {
…
this.quote = function() {
… this …
}.bind(this);
}
var app = new function () {
this.messages = [{
'author': 'Maya Angelou',
'quote': "If you don't like something, change it. If you can't change it, change your attitude."
}, {
'author': 'Richard Feynman',
'quote': "Hell, if I could explain it to the average person, it wouldn't have been worth the Nobel prize."
}, {
'author': 'Eddie Izzard',
'quote': "Cats have a scam going – you buy the food, they eat the food, they fuck off; that's the deal."
}, {
'author': 'George Carlin',
'quote': "I would never want to be a member of a group whose symbol was a man nailed to two pieces of wood. Especially if it's me!"
}];
this.textProp = 'textContent' in document.body ? 'textContent' : 'innerText';
this.outputTo = document.querySelector('#output');
this.trigger = document.querySelector('#load');
this.quote = function () {
var n = Math.floor(Math.random() * this.messages.length),
f = document.createElement('figure'),
c = document.createElement('figcaption'),
frag = document.createDocumentFragment();
f[this.textProp] = this.messages[n].quote;
c[this.textProp] = this.messages[n].author;
frag.appendChild(f);
frag.appendChild(c);
this.outputTo.innerHTML = '';
this.outputTo.appendChild(frag);
};
this.trigger.addEventListener('click', this.quote.bind(this));
};
var app = {};
app["messages"] = "test message";
app["textProp'] = 'textContent' in document.body ? 'textContent' : 'innerText';
app['quote']= function () {
var n = Math.floor(Math.random() * this.messages.length),
f = document.createElement('figure'),
c = document.createElement('figcaption'),
frag = document.createDocumentFragment();
f[app.textProp] = app.messages[n].quote;
}