说我有代码:
function Obj(){
var _x = 5;
this.getX = function(){
return _x;
};
}
var obj = new Obj();
function God(){
var x = obj.getX(); // i want 5 here
}
function Human(){
var x = obj.getX(); // i want error/undefined here
}
var x = obj.getX(); // i want error/undefined here too
如何隐藏除{1}以外的所有对象的getX
属性?
答案 0 :(得分:4)
假设您通过God
和Human
使用new God
和new Human
作为对象,则可以使用锁和键来允许使用正确的类型:
function Obj(lock) {
var _x = 5;
this.getX = function (key) {
if (key instanceof lock) {
return _x;
}
};
}
function God() {
var x = obj.getX(this);
console.log(x);
}
function Human() {
var x = obj.getX(this);
console.log(x);
}
var obj = new Obj(God);
var g = new God(); // logs 5
var h = new Human(); // logs undefined
当然,人们总是可以选择锁定:
function Thief() {
var g = new God();
var x = obj.getX(g);
}
var t = new Thief(); // logs 5
此锁定的另一种方法&关键机制是通过共享秘密:
function Obj(lock) {
var _x = 5;
this.getX = function (key) {
if (lock === key) {
return _x;
}
};
}
(function (scope) {
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
var secret = {};
scope.God = function () {
var x = scope.obj.getX(secret);
console.log(x);
};
scope.obj = new Obj(secret);
}(window));
function Human() {
var x = obj.getX();
console.log(x);
}
var g = new God();
var h = new Human();
答案 1 :(得分:0)
然后将该方法仅添加到一个对象
见下面的例子。
function K(){
this.name = 'Mr. K'
}
var k1 = new K()
k1.getX = function() {
console.log(this.name)
}
k1.getX(); // prints Mr.K
var k2 = new K()
k2.getX() // Error Uncaught TypeError: k2.getX is not a function

答案 2 :(得分:0)
单向:
参考:How do you find out the caller function in JavaScript?
检查Obj中的来电者功能名称,如上文所述,并采取相应的行动, 但不能在严格模式下使用。