2014-02-27 44 views
0

如何使用装饰没有访问object.defineProperty?AngularJS装饰没有object.defineProperty

我期待到可用的垫片:

但如果那些没有通过测试,有没有装修的目的是要工作的另一种方式?

我使用的装饰工具为$onRootScope

我使用角度1.08。我需要与IE7兼容。

更新

我已经试过了,似乎工作的一些方法,但我不知道他们之间的区别是:plunkr

var app = angular.module('plunker', []); 

app.config(['$provide', function($provide){ 
    $provide.decorator('$rootScope', ['$delegate', function($delegate){ 
    $delegate.a = 1; 
    $delegate.constructor.prototype.b = 2; 
    Object.defineProperty($delegate.constructor.prototype, 'c', { 
     value: 3 
    }); 
    return $delegate; 
    }]); 
}]); 

app.controller('MainCtrl', function($rootScope, $scope) { 
    console.log($rootScope); //reveals `a` property 
    console.log($rootScope.constructor.prototype); //=> {b:2, c:3} 
    console.log($rootScope.a); //=> 1 
    console.log($rootScope.b); //=> 2 
    console.log($rootScope.c); //=> 3 
    $scope.name = 'World'; 
}); 

谢谢。

+1

哟可以给你为什么认为你是被迫使用Object.defineProperty一个实例通过$ onRootScope创建一个装饰器? –

+0

@EdwinDalorzo它已经在问题了。我提到了如何定义$ onRootScope并使用'object.defineProperty()'的答案。我发现的其他例子也使用它。你有没有*不使用'object.defineProperty()'的例子? –

回答

0

好,同等解决方案的代码的PICE您共享是:

var proto = Object.getPrototypeOf(Object.getPrototypeOf($delegate)); 
proto['$onRootScope'] = function (name, listener) { 
    var unsubscribe = $delegate.$on(name, listener); 
    this.$on('$destroy', unsubscribe); 
}; 

在原来的这行代码$delegate.constructor.prototype越来越接近$委托的原型样机。

然后,一旦你访问它,你可以简单地定义一个新的功能。你不需要使用defineProperty。唯一需要注意的是,通过使用defineProperty,您可以配置该方法不可枚举(不应出现在for-each循环中)。以另一种方式,添加的方法将出现在for-each循环中。这对你来说可能不是问题。

我已为此创建了一个JSFiddle

可以使用John Resig's polyfillgetObjectPrototypeOf如果该功能不适用于当前的浏览器:

if (typeof Object.getPrototypeOf !== "function") { 
    if (typeof "test".__proto__ === "object") { 
    Object.getPrototypeOf = function(object){ 
     return object.__proto__; 
    }; 
    } else { 
    Object.getPrototypeOf = function(object){ 
     // May break if the constructor has been tampered with 
     return object.constructor.prototype; 
    }; 
    } 
} 
+0

不幸的是,这与作为object.defineProperty的[兼容性问题](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf)相同。但有趣的是,您只是使用简单的函数分配来提供'$ onRootScope'方法。为了获得原型,我可以只做'$ delegate.prototype.prototype'或'$ delegate.constructor.prototype.constructor.prototype'什么的? –

+0

或者我可以只是'$ delgate.constructor.prototype = {value:...}'? –

+0

@ ogc-nick您可以使用[John Resig的polyfill](http://ejohn.org/blog/objectgetprototypeof/)来执行'getPrototypeOf'。我编辑了我的答案。 –