无法调用在javascript中的对象内部定义的方法

时间:2018-06-21 22:03:25

标签: javascript

我已经定义了一个包含对象和函数数组的对象,并调用了以下方法:

var Person = {

  people: [{
      name: "Max",
      age: 41,
    },
    {
      name: "John",
      age: 25,

    },
    {
      name: "Doe",
      age: 67,

    },
  ],
  greeting: function() {
    return "Hello, my name is" + " " + this.name;
  }

};

function searchByName(namePerson) {

  var result = Person.people.find(Obj => Obj.name === namePerson);
  return result;
}

var max = searchByName('Max');
max.greeting();

我的函数定义有问题吗?运行时说“问候”不是功能。

3 个答案:

答案 0 :(得分:0)

您的代码没有多大意义,您的greeting函数位于外部Person对象上,但您正在使用它,就好像它是数组中每个人的属性一样。

您需要一个用于人员的构造函数,以便您可以使用Person方法实例化三个greeting

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greeting = function() {
  return "Hello, my name is " + this.name + " and I am " + this.age +  " years old";
}


const people = [
    new Person("Max", 41),
    new Person("JOhn", 25),
    new Person("Doe", 67), 
];

function searchByName(namePerson) {
  var result = people.find(obj => obj.name === namePerson);
  return result;
}

var max = searchByName('Max');
console.log(max.greeting());

答案 1 :(得分:0)

您可以将Person更改为可以用new Person()实例化的实际类。

//make the person class
function Person ( person ) {
  this.name = person.name;
  this.age = person.age;
}

//add the greeting method to the person class
Person.prototype.greeting = function () {
  return "Hello, my name is" + " " + this.name;
};

//build your people
var people = [
  new Person( { name: "Max", age: 41 } ),
  new Person( { name: "John", age: 25 } ),
  new Person( { name: "Doe", age: 67 } )
];

function searchByName(namePerson) {
  var result = people.find(person => person.name === namePerson);
  return result;
}

var max = searchByName('Max');
console.log( max.greeting() );

答案 2 :(得分:0)

您要返回的对象没有问候功能。

具有一点点不同结构的潜在不同解决方案就是这个。

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greeting = function() {
  return "Hello, my name is " + this.name;
}

function People(personArr) {
  this.people = personArr;
}

People.prototype.searchByName = function(name) {
  return this.people.find( person => person.name === name);
}

var people = new People([new Person("Max", 41), new Person("John", 25), new Person("Doe", 67)]);
var max = people.searchByName("Max");
console.log(max.greeting());