Hiding class methods with .call / .apply

Can someone explain what this excerpt from the Single Pages in depth means?

A common template for classes (for example, objects created from a prototype) is to simply classify class methods as private by running them with underscores. You can hide class methods using .call / .apply set to "this", but I will not show it here; this is a minor detail.

I think this suggests that there is a way to actually make JavaScript 'private' methods virtually inaccessible, instead of just pointing them to the underscore, but I can’t imagine what the implementation will look like and how it will be.

+5
source share
2 answers
var Treasure = function(){  
  function locate(){
    return this.x * this.y + 31337;
  }

  function Treasure(x, y){
    this.x = x;
    this.y = y;
  }

  Treasure.prototype.find = function find(){
    return locate.call(this);
  };

  return Treasure;
}();

locate- a common private function for constructor and prototype methods. Using call, he can act as a method and use this.

A more complete implementation of this concept is interface objects and implementation objects. Instead of having a few random functions-like-methods (similar to the location above), you actually create an entire class that is private. Each external interface creation creates two objects: an open shell interface and a private implementation object. This allows you to publish an interface that provides another, possibly easy-to-use API. Or it may allow you to reuse individual private implementation objects for entire groups of interface objects.

, DOM ( js, ). (, node), , , . , , .

Dom.js - DOM, js. , , . IDL: API , . , , , : https://github.com/Benvie/svgstuff/blob/master/lib/defs.js

+3

. , , :

function x() {
    var _var1 = "hello";
    this.var2 = "world";
    x.prototype.innerTest = function() {
        console.log("inner var1: " + _var1);
        console.log("inner var2: " + this.var2);
    }
}

var y = new x;
console.log("var1: " + y._var1);
console.log("var2: " + y.var2);

// var1: undefined
// var2: world

, var1 :

y.innerTest();
// var1: hello
// var2: world
+1

All Articles