caller - js私有的方法尝试

  因为一些业务要求,有这样的需求:

    a. 需要通过一个函数a new 另一个函数b.

    b. new 后的新函数,是放在一个对象c里.

    c. 有关b 的所有操作,都必须通过对象c 才可以.

  这样的需求,是为了保证我所操作的对象,都能够在能够掌握的范围内,并且不会脱离一些控制.

  其实做到 c 那一步的时候, 基本上大家就能够想到, 我们会用 caller . 但是, caller 怎么样获得他具体的对象? 因为他是放在 c 里面了的.

 

  经过尝试, 我给出了这样的一种折中方式

  a 是构造器

  a 必须通过 c 才能够被创建

  a 被创建后的对象是放在 list 中的. 

  只能够通过调用 list 的子集,才能够调用a 被创建的对象, 否则不可以 .

代码
var list = {};
function c(name){
var s0 = new a(name);
s0
&& (list[name] = s0);
}
function a(name){
if(a.caller != c){
return {
f:
false,g:false
}
}
this.name = name;
}
a.prototype
= {
f :
function(){
var p = this;
p.g();
},
g :
function(){
var p = this;
if(list[p.name].g.caller != list[p.name].f){
alert(
"no");
return;
}
alert(
"yes");
}
}
c(
"hehe");
list[
"hehe"].g();
list[
"hehe"].f();
var b = new a("yes");
for(var i in b){
alert(b[i]);
}

 

var list = {};
function c(name){
	var s0 = new a(name);
	s0 && (list[name] = s0);
}
function a(name){
        if(a.caller != c){
           return {
                f:false,g:false
           }
        }
	this.name = name;	
}
a.prototype = {
	f : function(){
		var p = this;
		p.g();
	},
	g : function(){
		var p = this;
		if(list[p.name].g.caller != list[p.name].f){
			alert("no");
			return;
		}
		alert("yes");
	}
}
c("hehe");
list["hehe"].g();
list["hehe"].f();
var b = new a("yes");
for(var i in b){
    alert(b[i]);
}

 

  我这里, 为了保证私自创建的 a 对象是不被许可的, 所以一开始,就更改了 a 里的子类. 由于a是一开始就是做为原形的存在, 所以修改他的子类后, 他的属性就不存在了.

  这样, 我们做了一个简单的, 模拟私有的尝试. 呵呵.

 

posted on 2010-12-21 10:00  Hehe123  阅读(1149)  评论(3编辑  收藏  举报