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

时间:2014-01-23 16:40:20

标签: 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?

4 个答案:

答案 0 :(得分:1)

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

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

<强>更新

var person = {
   setBasic: function(data) {
     alert(data.name + ' ' + data.age);

     this.getPerson = function() {
       alert('get me');
     };
   }
};

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

答案 1 :(得分:1)

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

/**
 * 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();
}

答案 2 :(得分:0)

试试这个

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

答案 3 :(得分:0)

其他答案都是有效的,但您也可以将代码重构为更简单:

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

Person.prototype.getData = function(){
    alert(this.name + " " + this.age);
};

var john = new Person({name: "John", age: 43});
john.getData();

一个JSFiddle来证明它有效here