简体   繁体   中英

Why can't I create a method equal to a global function within this object literal? (javascript)

Update: Thanks @Mathletics - I used an = when I should have used a : inside the object literal notation. setAge: setAge works perfectly inside the object literal.

In the Codecademy JavaScript track, the following problem occurs:

// 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;
bob.setAge = setAge;

// make susan here, and first give her an age of 25
//var susan = {age: 25, setAge = setAge}; //does not work
var susan = new Object();
susan.age = 25;
susan.setAge = setAge;

// here, update Susan's age to 35 using the method
susan.setAge(35);

I want to set susan.setAge to the global function, setAge . When I try to do it using object literal notation it does not work, but if I use new and then use dot notation it does work.

I tried setAge = global.setAge inside the object literal notation as well, but that failed. setAge = this.setAge , function setAge = setAge , function setAge = this.setAge and function setAge = global.setAge all also failed.

I tried researching related questions on Stack Overflow but those weren't very related. And this question , while about a similar example, seems to be about the author's confusion between creating a method within an object and calling a global method using .apply() , which he or she does not appear to be aware of.

Your sintax is wrong:

var susan = {age: 25, setAge : setAge}; // : instead of =
susan.setAge(35);
console.log(susan.age) // will show 35

You could also try a different approach:

function Person(params){
    params=params || {};
    this.age=params.hasOwnProperty("age") ? params.age : null;

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

var susan = new Person({age:25});
susan.setAge(35);
console.log(susan.age) // outputs 35

As you have mentioned, using arguments saves a few lines, as its always an object:

function Person(){
    this.age=arguments.hasOwnProperty("age") ? arguments["age"] : null;
    this.setAge=function(age){
        this.age=age;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM