javascript - 使用 Javascript 获取对象实例的变量值

标签 javascript jquery object instances

我有这个code snippet from MDN

然后,我添加了一些自己的代码,将 jQuery 单击事件附加到段落。

也许最好展示一下示例:

 function Person(first, last, age, gender, interests) {
      this.name = {
        'first': first,
        'last' : last
      };
      this.age = age;
      this.gen = gender;
      this.int = interests;
      this.nationality = "English";
      this.bio = function() {
        alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.int[0] + ' and ' + this.int[1] + '.');
      };
      this.greeting = function() {
        alert('Hi! I\'m ' + this.name.first + '.');
      };
      this.tt = function() {
        alert('Hi! I\'m ' + this.gen + '.');
      };  
    
      this.init= function() {
      	 $("p").click(function(){
      	  alert('Hi!');	//works fine
          alert('Hi! I\'m ' + this.name.first + '.');//obj.html:34 Uncaught TypeError: Cannot read property 'first' of undefined
         }); 
      };
    
      this.init(); //Bind to the P tag using jQuery click event
    
    }
    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    console.log(Person);
    person1.bio();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <p>My first paragraph.</p>
 

因此,当我单击 P 元素时,我会收到警报嗨!接下来是 Uncaught Error 消息。

如何获得第二个提醒“嗨!我是鲍勃”

最佳答案

有几种方法可以解决您的问题。 JavaScript 中的 this 关键字很棘手。你问题的核心是 this 不是你想象的那样。请参阅How does the "this" keyword work?了解更多详情。

1) 将 this 缓存到先前范围内的变量中。

this.init = function () {
  var self = this;
  $("p").click(function () {
    alert('Hi!');
    alert('Hi! I\'m ' + self.name.first + '.');
  });
};

2) 将 this 绑定(bind)到正在调用的函数

this.init = function () {
  var handleClick = function () {
    alert('Hi!');
    alert('Hi! I\'m ' + self.name.first + '.');
  };
  handleClick = handleClick.bind(this);
  $("p").click(handleClick);
}; 

关于javascript - 使用 Javascript 获取对象实例的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529359/

相关文章:

javascript - 无法使用 d3 选择 svg 元素

javascript - 为什么javascript中的数字键总是排序到开头?

php - jquery动态url

javascript - Vanilla JavaScript - Object.keys(object).forEach 仅显示最后一项

javascript - 从 Javascript 对象循环动态创建的表单。如何将数据保存回对象

javascript - 链接伪类变化时如何使用fadeIn/fadeOut?

javascript - 无法使用 jquery 设置选择的选定值

javascript - 未处理的拒绝(类型错误): Cannot read property of undefined

javascript - 我创建了一个可以对数字进行因式分解的网页。我已经创建了该功能。现在我需要创建一个函数来显示我的数学。

javascript - 鼠标单击事件切换类