javascript - 向js中函数内部的对象添加方法

标签 javascript function object constructor

您好,这是我正在处理的一项挑战。有什么方法可以在不使用关键字 this 的情况下将 introduce 方法添加到 personStore 对象。非常感谢任何见解。

Using Object.create

Challenge 1/3

Inside personStore object, create a property greet where the value is a function that logs "hello".

Challenge 2/3

Create a function personFromPersonStore that takes as input a name and an age. > When called, the function will create person objects using the Object.create method on the personStore object.

Challenge 3/3

Without editing the code you've already written, add an introduce method to the personStore object that logs "Hi, my name is [name]".

Side Curiosity

As a side note, was curious if there was a way to add the introduce method to the person object that sits inside of the personFromPersonStore function.

我的解决方案:

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function () {
  console.log('Hi, my name is ' + this.name)
}

//Challenge 3 Tester
sandra.introduce(); // -> Logs 'Hi, my name is Sandra

最佳答案

可以,但是使用 this 会简单得多。

此代码将 name 属性作为参数传递,但由于 introduce 函数已经可以通过 this 访问该属性作为内部属性>,有点浪费。

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function (nm) {
  console.log('Hi, my name is ' + nm)
}

person1=personFromPersonStore('Fred',21);
person1.introduce(person1.name);

关于javascript - 向js中函数内部的对象添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601046/

相关文章:

javascript - 每次调用对象中的任何函数时运行一个函数

javascript - NVD3 调度事件不适用于 HistoricalBarChart

LINQ 加入顶部 1

javascript - 如何在Web2py的 View 中访问python代码中的JavaScript变量

javascript - 带参数的 Angular JS ng-click

javascript - 为什么 JavaScript 中优先级较低的运算符会先执行?

python - 为什么我的 Python 函数不执行?

c - 如何将结构传递给 C 中的函数

object - Salesforce 对象和标准化

java - 简单的对象和方法