我有一个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/