簡體   English   中英

無法調用在javascript中的對象內部定義的方法

[英]Unable to call a method defined inside an object in 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(); 

我的函數定義有問題嗎? 運行時說“打招呼”不是功能。

您的代碼沒有多大意義,您的greeting函數在外部的Person對象上,但是您正在使用它,就好像它是數組中每個人的屬性一樣。

您需要一個用於人員的構造函數,以便可以使用greeting方法實例化三個Person

 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()); 

您可以將您的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() ); 

您要返回的對象沒有問候功能。

這是一個潛在的,具有不同結構的解決方案。

 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()); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM