Javascript OOP初始化和方法调用问题

标签 javascript oop initialization

我有一个javascript类person,我已经用它制作了Obj,工作正常。但我需要从 person 类访问该函数。

当我尝试访问时,我收到..not a function error

请帮忙!

重要...我需要初始化“person”类,并以与我的代码完全相同的方式调用该方法。如何??救命!

这是我的代码:

 var person = {
   setBasic: function(data) {
     alert(data.name + ' ' + data.age);
   },
   this:getPerson = function() {
     alert('get me');
   },
   success: null
 };

 //lets instantiate.enter code here

 var perObj = new person.setBasic({ 'name': 'ikair', 'age': 33, });

 // works fine..

 //now I need to call a function of person class:

 perObj.getPerson();

 //not working :(... how to call function with prev code?

最佳答案

您需要一个类并提供其原型(prototype)函数:

/**
 * Person class
 * @param {String} name Name of person
 * @param {Number} age Age of person
 */
function person(name, age) {
   this.name = name || "";
   this.age = age || 0;
   this.success = null;
}
person.prototype = {
   /**
    * Set the parameters of this object
    * @param {type} data
    * @returns {undefined}
    */
   setBasic: function(data) {
      this.name = data.name;
      this.age = data.age;

      alert(data.name + ' ' + data.age);
      // Do you mean to use this?
      alert(this.name + ' ' + this.age);
   },
   /**
    * Alert out fields
    * @returns {undefined}
    */
   getPerson: function() {
      alert(this.name + ' ' + this.age);
      alert('get me');
   }
};

/**
 * Make a person and print him out
 * @returns {undefined}
 */
function main() {
   var perObj = new person("bob", 33);
   perObj.setBasic({
      name: "akira",
      age: 100
   });
   perObj.getPerson();
}

关于Javascript OOP初始化和方法调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21314190/

相关文章:

javascript - 赫罗库 : Firebase can't load credentials

javascript - 使用 Blazor 重写 JavaScript 单击和显示 UI

php - fatal error : Uncaught Error: Call to a member function query() on null

java - Apache CollectionUtils 的良好用途

javascript - 这符合您对回调的定义吗?

c++ - new[] 是否初始化一个内置数组?

javascript - 如何修复错误 : listen EADDRINUSE while using NodeJS?

Javascript .indexOf 不适用于 int 数组

c - 使用三元运算符初始化结构

swift - 无法将类型 'CFTimeInterval.Type' 的值转换为 'CFTimeInterval'?