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

Getting variables value for an object instance using Javascript

我有这个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 元素时,我会收到警报,嗨!随后是未捕获的错误消息。

如何读取第二个警报,"Hi! I'm Bob"

如果您希望保留对 Person 对象的引用,则需要将 jQuery 回调函数与 thisBinding 绑定。

this.init= function() {
     $("p").click(function(){
      alert('Hi!'); //works fine
      alert('Hi! I\'m ' + this.name.first + '.');
     }.bind(this));//binding this prevents the error
  };

您需要将 this 绑定到您在 jquery click() 函数中传递的匿名函数。

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 + '.');
     }.bind(this)); 
  };

  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>

有几种方法可以解决您的问题。 this JavaScript 中的关键字很棘手。您问题的核心是 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 绑定到正在调用的函数中

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

另一种方法是在 jquery 函数外声明一个变量 name 并在函数内使用它

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

对变量使用 this 时要小心。 This, in your code refers to thePersoninstance. As soon as you create a new functionthisno longer references thePersonfunction, but thethis.initfunction, thusPerson` 在此上下文中不再存在。

而是用户 var name... 在使用变量时,您将能够在另一个上下文或函数中引用它:

<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
    <p>My first paragraph.</p>
    <script>
    function Person(first, last, age, gender, interests) {
      var name = {
        'first': first,
        'last' : last
      };
      var age = age;
      var gen = gender;
      var int = interests;
      var nationality = "English";
      this.bio = function() {
        alert(name.first + ' ' + name.last + ' is ' + age + ' years old. He likes ' + int[0] + ' and ' + int[1] + '.');
      };
      this.greeting = function() {
        alert('Hi! I\'m ' + name.first + '.');
      };
      this.tt = function() {
        alert('Hi! I\'m ' + gen + '.');
      };  
    
      this.init= function() {
        $("p").click(function(){
         alert('Hi!'); //works fine
          alert('Hi! I\'m ' + 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> 
    </body>
    </html>