js通过继承实现私有函数

时间:2023-03-08 23:41:36
js通过继承实现私有函数

本文是原创文章,如需转载,请注明文章出处

主要思想就是在继承时,只开放共有的属性和方法,不开放另外某些函数,从而实现私有的作用。

function A(){
this.x = 100;
this.y = 200;
this.f = function(){
console.log(this.x + this.y);
}
  //私有函数
this.g = function(){
console.log(this.x - this.y);
}
} function C(){
var a = new A();
var o = new Object();
o.x = a.x;
o.y = a.y;
o.f = a.f;
return o;
} function B(){ } B.prototype = C(); function run(){
var b = new B();
b.f();
}

C函数的作用就是剔除A中的私有函数(g),将其他的属性和方法放入o对象返回,之后将B的原型赋值给C返回的对象,这样当生成B对象时,只能访问到x,y,f了,从而实现私有函数g