Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Question

Post Timeline

edited tags
Link
Eric Herlitz
  • 26.4k
  • 28
  • 117
  • 167
Source Link
Eric Herlitz
  • 26.4k
  • 28
  • 117
  • 167

Replacing __proto__ with prototype

I tend to write my Javascript "classes" in c-style.

In C# (for example) we do this

public class Parent {
 // stuff
}
public class Child : Parent {
 // Protected and public stuff from Parent will be accessible
}

In JS I found the equivalent of this by using proto, in example

var namespace = namespace || {};
namespace.Parent = function() {
 
 // Public variables
 self.pubVariable = "I am accessible";
 
 // Private variables
 var priVariable = "I'm not accessible outside of self";
 
 // ctor
 function self() {}
 
 return self;
}
namespace.Child = (function() {
 this.__proto__ = new namespace.Parent();
 
 // ctor
 function self() {}
 
 self.init = function() {
 // Prints the pubVariable
 console.log(pubVariable);
 };
 
 return self;
 
})($);
// Call it (statically) 
namespace.Child.init();

While this works it is Webkit and Mozilla only. I've understood that this could somehow be achievable using prototype but can't figure out how. Any advice is appreciated. Thanks!

lang-js

AltStyle によって変換されたページ (->オリジナル) /