var app = angular.module('myapp', []); // Patterns for Enforcing new app.controller('MyCtrl', function($scope) { $scope.logs = []; function log() { $scope.logs.push(Array.prototype.slice.call(arguments).join('')); } // constructor function Waffle() { this.tastes = "yummy"; } // a new object var good_morning = new Waffle(); log('type of good_morning=', typeof good_morning); // object log('good_morning.tastes=', good_morning.tastes); // yummy // antipattern: forgotten `new` var not_good_morning = Waffle(); log("typeof not_good_morning=", typeof not_good_morning); // undefined log('window.tastes=', window.tastes); // "yummy" // that을 반환하면 된다. function ThatWaffle() { // var that = {}; // that.tastes = "gooood"; // return that; return { tastes: "gooood" }; } var that1 = new ThatWaffle(); var that2 = ThatWaffle(); log('that1.tastes=', that1.tastes); log('that2.tastes=', that2.tastes); // 하지만 생성자 프로토타입을 쓸모 없어졌다. ThatWaffle 프로토타입에 추가한 멤버는 사용할 수 없다. // Self-Invoking Constructor function SelfInvokeWaffle() { if (!(this instanceof SelfInvokeWaffle)) { return new SelfInvokeWaffle(); } this.tastes = "awesome"; } SelfInvokeWaffle.prototype.wantAnother = true; var first = new SelfInvokeWaffle(); var second = SelfInvokeWaffle(); log('first.tastes=', first.tastes); // awesome log('second.tastes=', first.tastes); // awesome log('first.wantAnother=', first.wantAnother); // true log('second.wantAnother=', first.wantAnother); // true });
<div ng-controller='MyCtrl'> <h4>Patterns for Enforcing new</h4> <ul> <li ng-repeat='log in logs'>{{log}}</li> </ul> </div>