我使用自定义框架:
var SForm = $A.support({
Name: 'SForm',
// instance based
// hidden, created by using this
// static based
S: {
google: 'https://plus.google.com/_/favicon?domain=',
pre_url: /(http:)|(https:)\/\//,
domain: /:\/\/(www\.)?([\.a-zA-Z0-9\-]+)/,
// the good parts has good url regex - implement it some time
url: /:\/\/(www\.)?[\x00-\x7F]{1,1800}\.[\x00-\x7F]{1,200}/,
email: /\S{1,64}@[\x00-\x7F]{1,255}\.[\x00-\x7F]{1,255}/,
tweet: /\S{1,40}/,
title: /\S{1,32}/,
name: /\S{1,64}/,
pass: /\S{6,20}/,
empty: /\S+/
},
constructor : function (form_elements) {
$A.someKey(form_elements, function (val) {
if (val.type !== 'checkbox') {
this.form_obj[val.name] = val.value;
} else if (val.type === 'checkbox') {
this.form_obj[val.name] = val.checked;
}
}, this);
},
// ... more
这对我有用,因为我可以稍微改变一下Java类系统。
但是我不知道如何使我的实例变量显式化,就像我的静态变量一样。
这是框架:
$P.block = $P.support = $P.parsel = function (obj, config_module) {
$R.Parsel[obj.Name] = obj;
// all properties are private
if (!config_module) {
return undefined;
}
// all properties are public
if (config_module === true) {
return obj;
}
// constructor based, all properties are public
if (config_module === 'constructor') {
var object_public;
if (obj.constructor) {
object_public = obj.constructor;
delete obj.constructor;
}
$A.someKey(obj, function (val, key) {
if (/^s_/.test(key)) {
object_public[key] = val;
} else if (/^p_/.test(key)) {
object_public.prototype[key] = val;
} else {
object_public.prototype[key] = val;
}
});
return object_public;
}
};
答案 0 :(得分:1)
我不太确定你的问题是什么,但看看你之前的问题,看起来你要么避免,要么不知道JavaScript的面向对象性质?
这是一个例子,我希望它可以帮到你。
// Define constructor function
function Child(name) {
// Check if "static" count exists.
if (typeof Child.count === "undefined") Child.count = 0;
// Assign instance variable
this.name = name;
Child.count++;
}
var alice, bob;
alice = new Child("Alice");
console.log(alice.name) // ==> "Alice"
console.log(Child.count) // ==> 1
bob = new Child("Bob");
console.log(alice.name) // ==> "Bob"
console.log(Child.count) // ==> 2
如果您确实希望私有变量在函数外部不可访问,则可以使用闭包将变量的范围限制为该范围。
var Child = (function() {
// Private static variable
var count = 0;
function constructor(name) {
// Public static variable
constructor.likes = ['toys', 'candy', 'pets', 'coloring'];
// Instance variable
this.name = name;
// Accessor methods
this.getCount = function() {
return count;
}
this.getLikes = function() {
return constructor.likes;
}
count++;
}
// Return the constructor function
return constructor;
})()