如何在我创建的对象文字中使用this关键字?

时间:2016-04-20 23:32:53

标签: javascript html

我一直遇到这个关键字的问题,虽然我已经阅读过很多关于在对象文字中使用 this 的帖子和文章,但它无效人们解释它的方式。我有一个名为 me 的对象,它有许多属性,我还有一个名为 bio 的方法,它将列出文本中的属性,并将其添加到变量中称为消息,最终将插入ID为摘要的div中。 bio方法在文本中使用了很多 this 关键字,当我尝试激活 me.bio 时,我收到错误消息。我知道如果我为替换关键字 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;

3 个答案:

答案 0 :(得分:2)

你遇到了一个常见的混乱。在下列情况下似乎是明智的:

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

函数调用f()将返回1,但是,不,它不会。 this在调用函数时受到约束,当您调用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建议手动进行绑定,这也很好。

答案 1 :(得分:1)

this指的是调用函数的上下文。

因为在单击按钮时正在调用me.bio并且正在按钮的onclick属性中存储,this实际上是按钮而不是对象me }。

如果您希望this对象me,则需要使用呼叫功能。

替换

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

document.querySelector('button#life').onclick = function(){me.bio.call(me)};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

答案 2 :(得分:1)

本文提供了关于此和闭包的非常好的解释。 http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

充分理解&#34;打电话&#34;,&#39;应用&#39;,&#39;绑定&#39;也会有所帮助。 http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

&#13;
&#13;
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(this.happiness > 75)
			  {
			    return 'happier than I have ever been';
			  }
			  else if (this.happiness < 75 && this.happiness > 50)
			  {
				return 'fairly satisfied with my life}';
			  
			  }
			  else if (this.happiness < 50 && this.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.bind(me);

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