gpt4 book ai didi

javascript - 如何让 this 关键字在我创建的对象字面量中起作用?

转载 作者:行者123 更新时间:2023-11-30 09:50:36 26 4
gpt4 key购买 nike

我一直在使用 this 关键字时遇到问题,虽然我已经阅读了很多关于在对象字面量中使用 this 的帖子和文章,但它在人们解释它的方式。我有一个名为 me 的对象,它有许多属性,我还有一个名为 bio 的方法,它将在文本中列出属性并将其添加到变量中称为 message,最终将被插入到 ID 为 summary 的 div 中。 bio 方法在文本中使用了很多this 关键字,当我尝试激活me.bio 时,我收到错误消息。我知道如果我为 me 替换关键字 this 它会正常运行。但是,我真的需要知道在制作对象文字时如何正确使用 this 关键字。这是我在 JSFiddle 中的代码

HTML

<div id="ex1">
<h2>Ajax and Objects</h2>
<p>
I created an object about myself and added around 12 or so properties about me and two methods about myself as well
</p>


<h4>The Buttons of My Life:</h4>
<button id="life">My Normal Life</button>
<button id="ajaxLife">My Life Now... with AJAX</button>


</div>

<div id="summary"></div>

Javascript

var me = {

fName: 'George',
lName: 'Walsh',
job: { name: 'Retail Clerk', pay: 9.50, company:'Harbor Freight Tools', enjoyJob:false},
age: 26,
height: '6\'0',
happiness: 48,
happyState : function()
{
if(me.happiness > 75)
{
return 'happier than I have ever been';
}
else if (me.happiness < 75 && me.happiness > 50)
{
return 'fairly satisfied with my life}';

}
else if (me.happiness < 50 && me.happiness > 25)
{
return 'not in a good place with my life';
}
else{

return 'thinking about killing myself';

}
}
,
virgin: true,
weight: 230,
bio : function()
{
var message;
var m;
message = '<p>Hello, my name is '+this.fName+' '+this.lName+'</p>';
message += '<p> I am '+this.age+' years old</p>';
m = (this.job.enjoyJob == true)? 'awesome': 'shitty';
message += '<p> And I work at a '+ m +' job called '+this.job.company+' and\
I only get paid '+this.job.pay+' an hour and my position is a '+this.job.name+'</p>';
m =(this.virgin == true)? 'I have not dipped my penis in the soft walls of a vagina':'I am not a virgin anymore and I\'m fucking like crazy';
message += '<p> I am currently '+this.happyState()+' and '+ m +' </p>';
message += '<p> I also weigh '+this.weight+' </p>';

document.querySelector('div#summary').innerHTML = message;


}



}


document.querySelector('button#life').onclick = me.bio;

document.querySelector('button#ajaxLife').onclick = loadAjax;

最佳答案

您遇到了一个常见的困惑。在以下情况下似乎是明智的:

var p = {
a : 1,
m : function() { return this.a }
}
var f = p.m
f()

函数调用 f() 会返回 1,但是,不,它不会。 this 绑定(bind)在函数调用点,当你调用 f() 时,this 是全局上下文,this .a 可能未定义。

考虑:

var p = {
a : 1,
m : function() { return this.a }
}
var q = {
a : 2,
m : p.m
}
q.m()

这里,q.m() 将返回 2。

您的解决方案使用命名变量代替 this,与其他解决方案一样好,但 QoP 提出了另一个解决方案。

如果您提到自己的情绪状态是在开玩笑,您可能应该学会讲更好的笑话;如果没有,您可能会寻求专业帮助。

编辑

QoP 无缘无故地删除了他的答案,但它看起来像这样:

document.querySelector('button#life').onclick = me.bio.bind(me);

bind 完全适合您的目的,但它仅在 ECMA-262 第 5 版(2009 年)中可用,因此非常老旧的 hooptie 浏览器将不支持它。考虑使用 polyfill .

Reuben 建议手动绑定(bind),这也很好。

关于javascript - 如何让 this 关键字在我创建的对象字面量中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757036/

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