[英]Working with JS objects and functions
I'm a newbie in javascript and I'm wondering why bob.age
is still 30 while age
is 50 when I called it. 我是javascript的新手,我想知道为什么bob.age
在我叫50 age
仍然是30 age
。 I already set age
to 50 in setAge
that assigned 50 to this.age
, which I know is a reference to bob.age
, so age
and bob.age
should have the same value. 我已经在setAge
中将age
设置为50, setAge
50分配给this.age
,我知道这是对bob.age
的引用,因此age
和bob.age
应该具有相同的值。
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
// change bob's age to 50 here
bob.setAge = setAge(50);
There're several errors in your code/understanding, I'm going to start with why that is specifically wrong, and explain the concepts around it 您的代码/理解中有几个错误,我将首先说明为什么这是特别错误的,并解释其周围的概念
var bob = new Object()
is making bob a regular object. var bob = new Object()
使bob成为常规对象。
your setAge
function takes in a parameter. 您的setAge
函数接受一个参数。 It sets this.age
to be that value. 它将this.age
设置this.age
值。 However setAge is placed on the global scope. 但是setAge放在全局范围内。 Therefore this
-> window
. 因此, this
-> window
。 Which is why when your typed in age
in the global scope you got 50. 这就是为什么当您在全球范围内输入age
时会得到50。
Jaromanda is correct, you need to place the function setAge
onto the object bob. Jaromanda是正确的,您需要将setAge
函数setAge
到对象bob上。
If you're playing around with this
you may be interested in the pseudoclassical instantiation style: 如果您正在玩this
游戏,那么您可能会对伪经典实例化样式感兴趣:
var Person = function(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setAge = function(newAge) {
this.age = newAge;
}
var bob = new Person ('Bob', 30);
bob.setAge(50);
bob.age;
// 50
bob.setAge = setAge(50); bob.setAge = setAge(50);
all that is doing is setting the setAge property of bob to the result of calling setAge(50) - as setAge retunrs undefined, you've effectively set bob.SetAge = undefined. 所有要做的就是将bob的setAge属性设置为调用setAge(50)的结果-由于setAge retunrs未定义,您已经有效地设置了bob.SetAge = undefined。 Perhaps what you intended to do was 也许你打算做的是
bob.setAge = setAge;
bob.setAge(50);
untested, but I think it's right 未经测试,但我认为是对的
The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used. 关键字this充当占位符,并且在实际使用该方法时将引用该方法所引用的任何对象 。
Look at the method setAge to see how this works. 查看方法setAge以了解其工作原理。 By using the keyword this , setAge will change the age property of any object that calls it. 通过使用关键字this , setAge将更改任何调用它的对象的age属性。
Then when we say bob.setAge = setAge ; 然后,当我们说bob.setAge = setAge时 ; it means whenever we type bob.setAge( ) this.age in the setAge method will refer to bob.age. 这意味着每当我们键入bob.setAge()this.age在setAge方法将参考bob.age。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.