然后,我添加了一些自己的代码,将 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/