Noob Concern:JavaScript函数用法

Mon*_*an5 6 javascript function

我正在阅读JavaScript教程,我可以完成它.但问题是我不明白其中一条线在做什么.我有一个函数setAge(),然后在创建一个susan对象后,我将该对象的一个​​属性设置为函数的名称?我不明白为什么这样做.如果不这样做,我不能使用函数/方法吗?

教程代码:

var setAge = function (newAge) {
  this.age = newAge;
};

var susan = new Object(); 
susan.age = 25; 
susan.setAge = setAge; //how the hell does this work?  

// here, update Susan's age to 35 using the method
susan.setAge(35); 
Run Code Online (Sandbox Code Playgroud)

Tin*_*ehr 8

它将susan属性分配给setAge上面定义的函数,

function (newAge) {
  this.age = newAge;
};
Run Code Online (Sandbox Code Playgroud)

这是一个接受一个参数的函数.当susan.setAge(35);被叫时,this将参考呼叫者susan,将她的年龄更新为35岁.

混淆可能来自setAge两次使用.Susan的功能在左侧定义,右侧已定义.例如:

susan.letMyAgeBe = setAge; 
susan.letMyAgeBe(35); 
Run Code Online (Sandbox Code Playgroud)

工作原理相同.setAge也是"可重复使用的":

harry = new Object();
harry.iAmThisOld = setAge;
harry.iAmThisOld(55);
Run Code Online (Sandbox Code Playgroud)

演示 http://jsfiddle.net/7JbKY/2/