【发布时间】:2018-03-21 23:21:10
【问题描述】:
我在这个练习中遇到过,但我不知道如何解决 CHALLENGE 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”
【问题讨论】:
-
您是否尝试将其添加到对象的原型中?即
PersonConstructor.prototype.introduce = function() {,然后是console.log("Hi, my name is" + this.name) -
@activedecay 没关系
-
@seesharper 没关系,但需要大量编辑才能使其清晰易读。我为什么要读 cmets?
标签: javascript oop methods