实习招聘面试经历-2
1. Angular双向绑定的实现嗯…面试三次,每个面试官都会问我这个问题,这里还是贴一下参考的文章吧:Angular沉思录(一) 数据的双向绑定AngularJS 数据双向绑定揭秘简易实现版本:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263var Scope = function () { this.$$watchers = [];}Scope.prototype.$watch = function( watchExp, listener ) { this.$$watchers.push( { watchExp: watchExp, listener: listener || function () {} });};Scope.prototype.$digest = function() { var dirty; do { dirty = false; for (var i = this.$$watchers.length - 1; i >= 0; i--) { var newValue = this.$$watchers[i].watchExp(), oldValue = this.$$watchers[i].last; if( oldValue !== newValue) { this.$$watchers[i].listener(newValue, oldValue); dirty = true; this.$$watchers[i].last = newValue; } }; } while(dirty);};var $scope = new Scope();$scope.name = 'Ryan';$scope.$watch(function () { return $scope.name;}, function ( newValue, oldValue ) { console.log('Input Value has update:' + newValue + ' and Old Value is: ' + oldValue); element[0].value = newValue; tips.innerHTML = newValue});/** 视图到模型 **/var element = document.querySelectorAll('input'), tips = document.querySelectorAll('#tips')[0];element[0].addEventListener('keyup', function () { $scope.name = element[0].value; $scope.$digest();})/** 模型到视图 **/var updateScopeValue = function () { $scope.name = 'Bob'; $scope.$digest();}var btn = document.getElementsByTagName('button')[0];btn.addEventListener('click', function () { updateScopeValue();})