如何限制子对象在JavaScript中调用父函数?

时间:2018-06-22 12:45:20

标签: javascript inheritance

如何限制子对象在继承时不能调用父函数?

var Parent = function() {};

Parent.prototype.myF = function() {
  console.log('derp');
};

function Child() {};

//make [[prototype]] of Child be a ref to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
Child.prototype.getName = function() {
  console.log('dddd')
}

var c = new Child();
c.myF();

我希望子类无法在myF();中调用Java使其成为private。我可以用JavaScript做到吗?

2 个答案:

答案 0 :(得分:0)

JavaScript中没有私有成员。但是,按照惯例,您可以模拟私有成员并模仿预期的行为。

使用前缀

function Child() {
    // underscore prefix
    this._var = 42;
}

var child = new Child();

console.log(child.var); // undefined
console.log(child._var); // 42

function Child() {
    // underscore prefix
    this._prop = 42
}

Child.prototype.getProp = function() {
    return this._prop;
};

var child = new Child();

console.log(child.prop); // undefined
console.log(child._prop); // 42
console.log(child.getProp()) // 42

使用闭包

function Child() {
    // this variable cannot be accessed 
    // directly from outside
    var prop = 42;
    
    this.getProp = function() {
        return prop;
    }
}

var child = new Child();

console.log(child.prop); // undefined
console.log(child.getProp()); // 42

将来的JavaScript中的私有方法

this tc39 proposal如此被接受并实现后,您就可以在JavaScript中定义私有方法和字段。


以您的情况

var Parent = function() {};

Parent.prototype._myF = function() {
  console.log('derp');
};

var Child = function() {};

Child.prototype = Object.create(Parent.prototype);
Child.prototype.getName = function() {
  console.log('dddd')
}

// usage

var p = new Parent();
// notice the underscore prefix (_)
p._myF(); // "derp"

var c = new Child();
c.getName(); // "dddd"
c.myF(); // Uncaught TypeError: c.myF is not a function

但是您将可以通过孩子_myF()来访问通过孩子的父母的功能c._myF();。这就是为什么在JavaScript的当前状态下,如果要使用私有成员,则必须遵守约定,每个带下划线前缀的成员都应视为私有

答案 1 :(得分:0)

它们还不是javascript中的私有字段,但是当前tc39正在处理该问题,您必须等待下一个Ecmascript标准private fields,或者您可以使用将代码转换为一些奇怪内容的编译器大脑无法破译。但这可能会解决您的问题,如果是父项或子项,则必须检查构造函数属性

function Parent() {};

Parent.prototype.doThis = function() {
    if ( this.constructor.name != "Parent" )
        throw new Error("You are not allowed to call this method");
    console.log("derp");
};

function Child() {};

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

Child.prototype.getName = function() {
    console.log("ddd");
};

let p = new Parent();
let c = new Child();


console.log(p.doThis());
console.log(c.getName());
console.log(c.doThis());
相关问题