2

The first lesson is scope.

var scope = "global";
function Scope() {
    var scope = "local";
    this.s = function() { return scope; }
}
var instance = new Scope();
console.log(instance.scope); ///this is 'undefined' 
console.log(instance.s()); /// this is 'local'

This makes sense in the world of closures.

Then BaseScope is introduced.

function BaseScope() {
    this.scope = "parent";
    this.h = function() {return "Hello";}
}
Scope.prototype = Object.create(BaseScope);

So now, I want to add the prototype of BaseScope to Scope. The below, is what I WANT to be returned.

var instance2 = new Scope();
console.log(instance2.s()); ///Should be returning 'local' because it is the  fastest returned s() function on the object's prototype.
console.log(instance2.scope); ///Should be returning BaseScope's scope, since it is technically the only defined 'scope' property up the chain.
console.log(instance2.h()); ///Should return "Hello"

The last example is returning undefined which makes me think I am doing something completely wrong. What steps should I take to get the desired effect above?

christopher clark
  • 2,026
  • 5
  • 28
  • 47

1 Answers1

3

You can access basescope on scope prototype as

scope.prototype=Object.create(BaseScope.prototype);

and if you want to have access to BaseScope's scope variable all you need is call BaseScope from Scope ,it can be done using BaseScope.call(this),using call you can change the scope of this .

check this snippet

function Scope() {
  BaseScope.call(this);
  var scope = "local";
  this.s = function() {
    return scope;
  }
}

function BaseScope() {

  this.scope = "parent";
  this.h = function() {
    return "Hello";
  }
}
Scope.prototype = Object.create(BaseScope.prototype);

var instance = new Scope();
console.log(instance.scope); ///this is 'undefined' 
console.log(instance.s());
console.log(instance.h());
Sreekanth
  • 3,110
  • 10
  • 22
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • 1
    The line `Scope.prototype = Object.create( BaseScope.prototype);` seems unnecessary, since these objects do not deal with prototype chain at all. – Kuba Wyrostek Dec 01 '16 at 18:35
  • 1
    How would I do this without putting `BaseScope.call(this)` into the `Scope()` definition – christopher clark Dec 01 '16 at 18:36
  • you cannot have access to BaseScope's variables without changing its context ...it cannot be done using call/apply...check this link http://stackoverflow.com/questions/39417710/confusion-with-javascript-inheritance – Geeky Dec 01 '16 at 18:40
  • As OP wants to establish parent child relation ...which is inheritance i guess it can be done by setting their prototype – Geeky Dec 01 '16 at 18:40