var app = angular.module('myapp', []); // Custom Constructor Functions app.controller('MyCtrl', function($scope) { var Person = function (name) { this.name = name; this.say = function () { return "I am " + this.name; }; }; var adam = new Person("Adam"); // new와 함께 생성자 함수 호출시 함수 안에서 발생하는 일 // * 빈 객체 생성. 이 객체는 this로 참조할 수 있으며, 해당 함수의 프로토타입을 상속받는다. // * this로 참조되는 객체에 프로퍼티와 메서드가 추가된다. // * 다른 객체가 명시적으로 반환되지 않을 경우 this로 참조된 객체가 반환된다. /* var Person = function (name) { // create a new object using the object literal // var this = {}; // add properties and methods this.name = name; this.say = function () { return "I am " + this.name; }; return this; }; */ // 여기서 say()는 this에 할당되므로 new Person()할 때마다 새로운 say()함수가 만들어진다. // 비효율적이므로 Person의 prototype에 추가하는 것이 낫다. Person.prototype.protoSay = function() { return "I am proto " + this.name; }; $scope.say = adam.say(); // I am Adam $scope.protoSay = adam.protoSay(); // I am Adam // 위에서 var this = {} 라고 했지만 더 정확히는 // var this = Object.create(Person.prototype); 에 더 가깝다. // 즉 함수의 프로토타입을 상속받는다. // 아래는 생성자에서 this가 아닌 다른 객체를 return하는 경우. var ObjectMaker = function () { // this `name` property will be ignored because the constructor // decides to return another object instead this.name = "This is it"; // creating and returning a new object var that = {}; that.name = "And that's that"; return that; }; $scope.that = new ObjectMaker(); // 아래와 같이 문자열이나 false 같이 객체가 아닌 것을 반환하면 에러가 나진 않지만 무시되고 this가 반환된다. var StringMaker = function() { this.name = "I am a string"; return "how about string ?"; }; $scope.str = new StringMaker(); var BooleanMaker = function() { this.name = "I am a boolean"; return false; }; $scope.boolObj = new BooleanMaker(); });
<div ng-controller='MyCtrl'> <h4>Custom Constructor Functions</h4> <ul> <li>adam.say: {{say}}</li> <li>adam.protoSay: {{protoSay}}</li> <li>that.name: {{that.name}}</li> <li>str: {{str}}</li> <li>boolObj: {{boolObj}}</li> </ul> </div>