var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(50);
基本上,代码以更改年龄属性的方法开始,然后该方法后面跟着一个“bob”对象,最后是使用该方法更改 bob 属性(年龄)的代码。
我有两个问题:bob.setAge = setAge; (代码中倒数第二行)
通过将setAge设置为等于bob.setAge,这不是将setAge设置为全局变量,等于bob.setAge吗?
在bob.setAge中,bob是变量,setAge是方法。我认为在写出像 bob.setAge 这样的东西时,句点之前的单词引用对象(susan.age),句点之后的单词引用属性(susan.<强>年龄)。 javascript 如何识别 bob.setAge 中的 setAge 引用的是方法而不是属性?
最佳答案
By setting setAge equal to bob.setAge, doesn't this set setAge to a global variable, equalling bob.setAge?
不,你正在做相反的事情
In bob.setAge, bob is the variable, and setAge is the method. I thought that when writing out something like bob.setAge, the word that comes before the period references the object (susan.age), and the word that comes after the period references a property (susan.age). How does javascript recognize that the setAge in bob.setAge references a method and not a property?
JS 无法“识别它”(它不区分“它们”,因为“它们”是同一件事):bob.setAge
保存对您可以使用的函数的引用(并且你这样做)调用
关于javascript - 在处理 Javascript 中的方法时,为什么不设置全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552832/