$scope inheritance

by mslocum

JavaScript

// This is almost identical to what angular does, but simpler.
// $scope uses prototype inheritance. I'm going to mimic it.
// https://github.com/angular/angular.js/blob/v1.3.18/src/ng/rootScope.js#L224

function Scope() {}
Scope.prototype.$new = function() {
    var Child = function(){};
    // We are simply using prototypical inheritance. Nothing angular here.
    Child.prototype = this;
    return new Child();
}

// We aren't using angular at all. I'm just using angular looking variables to look familiar.
var $rootScope = new Scope();
var $scope1 = $rootScope.$new();
var $scope2 = $scope1.$new();


$scope1.val = 1;
alert("$scope2 can read val from $scope1: " + $scope2.val);
$scope2.val = 2;
alert("$scope1 remains unchanged after editing $scope2: " + $scope1.val);


$scope1.obj = {
    a: 1
}
$scope2.obj.a = 2;

alert("$scope1's obj.a got changed because prototypes do lookups left to right before assignments: " + $scope1.obj.a);