如何为函数添加方法?

时间:2018-03-21 23:21:11

标签: javascript oop methods

我在这次演习中遇到过,我不知道如何解决挑战3。



/*Create a function PersonConstructor that uses the this keyword to save a single property onto its scope called
     greet. greet should be a function that logs the string 'hello'.*/
function PersonConstructor() {
  this.greet = function() {
    console.log('hello!');
  }
}

var simon = new PersonConstructor;

simon.greet(); // -> Logs 'hello'

/*** CHALLENGE 2 of 3 ***/
/*Create a function personFromConstructor that takes as input a name and an age. When called, the function will create
 person objects using the new keyword instead of the Object.create method.*/

function personFromConstructor(name, age) {
  var personObj = new PersonConstructor;
  personObj.name = name;
  personObj.age = age;
  return personObj;
}

var mike = personFromConstructor('Mike', 30);

console.log(mike.name); // -> Logs 'Mike'
console.log(mike.age); //-> Logs 30
mike.greet(); //-> Logs 'hello'

/*** CHALLENGE 3 of 3 ***/
/*Without editing the code you've already written, add an introduce method to the PersonConstructor function that logs
 "Hi, my name is [name]".*/
PersonConstructor.introduce = function() {
  console.log("Hi, my name is ");
};
mike.introduce(); // -> Logs 'Hi, my name is Mike' // doesn't work




如何向函数PersonConstructor添加方法? mike.introduce()应该记录// - >记录'您好,我的名字是Mike'

1 个答案:

答案 0 :(得分:3)

您需要将该函数添加到类的原型中,因此它将应用于所有对象。它可以使用this.name来访问对象的属性。



/*Create a function PersonConstructor that uses the this keyword to save a single property onto its scope called
     greet. greet should be a function that logs the string 'hello'.*/
function PersonConstructor() {
  this.greet = function() {
    console.log('hello!');
  }
}

var simon = new PersonConstructor;

simon.greet(); // -> Logs 'hello'

/*** CHALLENGE 2 of 3 ***/
/*Create a function personFromConstructor that takes as input a name and an age. When called, the function will create
 person objects using the new keyword instead of the Object.create method.*/

function personFromConstructor(name, age) {
  var personObj = new PersonConstructor;
  personObj.name = name;
  personObj.age = age;
  return personObj;
}

var mike = personFromConstructor('Mike', 30);

console.log(mike.name); // -> Logs 'Mike'
console.log(mike.age); //-> Logs 30
mike.greet(); //-> Logs 'hello'

/*** CHALLENGE 3 of 3 ***/
/*Without editing the code you've already written, add an introduce method to the PersonConstructor function that logs
 "Hi, my name is [name]".*/
PersonConstructor.prototype.introduce = function() {
  console.log("Hi, my name is " + this.name);
};
mike.introduce(); // -> Logs 'Hi, my name is Mike' // doesn't work