综合开发

Is it possible to add functions to a class JS that has access to the private variables of t…

微信扫一扫,分享到朋友圈

Is it possible to add functions to a class JS that has access to the private variables of t…

I have an existing class I need to convert so I can append functions like my_class.prototype.my_funcs.afucntion = function(){ alert(private_var);}
after the main object definition. What’s the best/easiest method for converting an existing class to use this method? Currently I have a JavaScript object constructed like this:

var my_class = function (){
var private_var = '';
var private_int = 0
var private_var2 = '';
[...]
var private_func1 = function(id) {
return document.getElementById(id);
};
var private_func2 = function(id) {
alert(id);
};
return{
public_func1: function(){
},
my_funcs: {
do_this: function{
},
do_that: function(){
}
}
}
}();

Unfortunately, currently, I need to dynamically add functions and methods to this object with PHP based on user selected settings, there could be no functions added or 50. This is making adding features very complicated because to add a my_class.my_funcs.afunction();
function, I have to add a PHP call inside the JS file so it can access the private variables
, and it just makes everything so messy.

I want to be able to use the prototype method so I can clean out all of the PHP calls inside the main JS file.

Try declaring your “Class” like this:

var MyClass = function () {
// Private variables and functions
var privateVar = '',
privateNum = 0,
privateVar2 = '',
privateFn = function (arg) {
return arg + privateNum;
};
// Public variables and functions
this.publicVar = '';
this.publicNum = 0;
this.publicVar2 = '';
this.publicFn = function () {
return 'foo';
};
this.publicObject = {
'property': 'value',
'fn': function () {
return 'bar';
}
};
};

You can augment this object by adding properties to its prototype (but they won’t be accessible unless you create an instance of this class)

MyClass.prototype.aFunction = function (arg1, arg2) {
return arg1 + arg2 + this.publicNum;
// Has access to public members of the current instance
};

Helpful?

Edit:Make sure you create an instance of MyClass
or nothing will work properly.

// Correct
var instance = new MyClass();
instance.publicFn(); //-> 'foo'
// Incorrect
MyClass.publicFn(); //-> TypeError

Apple Updates 'Apple Developer' App With New Video Features Ahead of Digital WWDC

上一篇

Nominate an Awesome Community Chef!

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Is it possible to add functions to a class JS that has access to the private variables of t…

长按储存图像,分享给朋友