`
ericwzc
  • 浏览: 11890 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Javascript in one example

阅读更多

本文通过解决一个问题,引出javascript的概况

 

问题:  有两种不同的视图,界面上有个按钮供点击来实现视图间的切换

最直观也简单的想法:

var cur = 1;
function view1(){}
function view2(){}
function control(){
   window['view' + cur](); 
   cur = cur > 1 ? 1 : 2;
}
control();
control();
control();
control();

思考一下,有个全局变量总是不爽, 设想某个函数

function evilF(){
  cur = 0;
}

那么我们的control函数就成了受害者了.  所以要想法把cur藏起来,试试面向对象如何?因为封装是其特色之一。  

function F(start){  
  this.cur = start;   
}
F.prototype.control = function(){
   window['view' + this.cur](); 
   this.cur = this.cur > 1 ? 1 : 2;
};
var controller = new F(1);
controller.cur = 3; //Oops
controller.control();

顺便做了一个小改进, 用户可以指定从那个页面开始了。结果报错了,问题是我们还能改cur的值。 难道就无计可施了吗? 该闭包闪亮登场了!(It's show time for closure!)

function F(start){
  var obj = {};
  obj.control = function(){   
   window['view' + start](); 
   start = start > 1 ? 1 : 2;
  };
  function P(){}   
  P.prototype = obj;
  return new P();
}

var controller = new F(1);
controller.start = 3;
controller.control();
controller.control();
controller.control = function(){console.log('blahblah');};
controller.control();
delete controller.control; // allow control to shine through from prototype.
controller.control();

万事大吉,除非用户把control给覆盖掉了,这样原型里面的就找不到了,当删掉自定义的之后,一切恢复如初。

换个角度来思考, 这个问题跟什么比较类似呢?日历!

日历的提示,无非是从周一到周日循环复始而已,我们想要的正是类似的功能。我们也可以写一个生成器函数,把这种思想推而广之。

function func_generator(funcs, start){                            
   start = start || 0;
   funcs = funcs || [];
   var len = funcs.length;
   return function () {
        if(!len){
           return undefined;
        }
        if(start >= len){
           start %= len;
        }
        return funcs[start++] ;
   };
}

var view_toggler = func_generator([function (){console.log('view1');}, function(){console.log('view2');}], 1);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);

事情好起来了,除非用户把func_generator 给重写了, 为防止别人无心破环我们的成果, 再多做出一点努力把,把名字放长一点,打个包

var toolkit = (function(){
  return {   
    func_generator: function(funcs, start){                            
     start = start || 0;
     start = start < 0 ? 0 : start; 
     funcs = funcs || [];
     var len = funcs.length;
     return function () {
        if(!len){
           return undefined;
        }
        if(start >= len){
           start %= len;
        }
        return funcs[start++] ;
     };  
    }
  };
})();
var view_toggler = toolkit.func_generator([function (){console.log('view1');}, function(){console.log('view2');}], 0);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);
view_toggler().apply(null,[]);

现在用户把我们的toolkit搞砸的概率大大减小了。

 

再多做一点, 让用户可以自由指定从那里开始切换

var toolkit = (function(){  
  return {     
    func_generator: function(funcs, start){                              
     start = start || 0; 
     start = start < 0 ? 0 : start; 
     funcs = funcs || [];  
     var len = funcs.length;  
     return function () {  
        if(!len){  
           return undefined;  
        }    
        if(arguments.length){
          start = arguments[0];
        }    
        if(start >= len){  
           start %= len;  
        }         
        return funcs[start++] ;  
     };    
    }  
  };  
})();  
var view_toggler = toolkit.func_generator([function (){console.log('view1');}, function(){console.log('view2');}, 
function(){console.log('view3');}, function(){console.log('view4');}], 0);  
view_toggler().apply(null,[]);  
view_toggler().apply(null,[]);  
view_toggler().apply(null,[]);  
view_toggler(0).apply(null,[]);  
view_toggler().apply(null,[]);  
view_toggler().apply(null,[]);  
view_toggler().apply(null,[]);  
view_toggler().apply(null,[]); 
 

 

分享到:
评论

相关推荐

    React Native By Example

    He currently works for Capital One and has taught software engineers at Hack Reactor in the past. Richard is also a technical advisor to Code Chrysalis, an advanced software engineering immersive in ...

    JavaScript Next.pdf

    As you progress through the book, you’ll be offered multiple opportunities to see the new features in action, and in concert with one another. Backed by an example-driven writing style, you’ll ...

    Practical JavaScript, DOM Scripting and Ajax Projects

    One of the main premises of this book is to help you learn by example so you can then apply your knowledge to your own projects. This book will save you countless hours of development time and help ...

    AngularJS by Example-Packt Publishing 2015

    AngularJS makes web JavaScript web development less painful and more organized – it's unsurprising that today it's one of the most popular tools in web development. AngularJS by Example helps you get...

    AngularJS by Example(PACKT,2015)

    AngularJS makes web JavaScript web development less painful and more organized – it's unsurprising that today it's one of the most popular tools in web development. AngularJS by Example helps you ...

    Node.js.By.Example.1784395714.epub

    Node.js By Example covers Node.js fundamentals and teaches you how to use its technology to architect a project. It shows you how to manage an application's assets and how to implement the Model-View-...

    Flask By Example.pdf 最新 原版

    If your answer to any one of these questions is a yes, then this is just the book for you. It is also intended for people who know the basics of Python and want to learn how to use it to build ...

    Learning Three.js: The Javascript 3D Library for WebGL

    "Learning Three.js: The JavaScript 3D Library for WebGL" is a practical, example-rich book that will help you to master all the features of Three.js. With this book, you’ll learn how to create and ...

    Vue.js 2.x by Example

    Starting with a JSON dataset, the first part of the book covers Vue objects and how to utilize each one. This will be covered by exploring different ways of displaying data from a JSON dataset. We ...

    Node.js By Example(PACKT,2015)

    Node.js is a JavaScript - driven technology, which means that developers can use the same language to write backend code. Its growing community and the large amount of available modules make Node.js ...

    angularJs by example

    it's unsurprising that today it's one of the most popular tools in web development., AngularJS by Example helps you get started with this essential web development framework quickly and easily, ...

    node in action

    Node.js in Action is an example-driven tutorial that starts at square one and goes through all the features, techniques, and concepts needed to build production-quality Node applications. First it ...

    JavaScript 基础问答三

    包括在/* 和 */ 内的内容都是注释,例如: /* This is a comment */ /* C-style comments can span as many lines as you like, as shown in this example */ C++样式的单行注释。这些注释以//开始,到行尾结束: /...

    AngularJS by Example(pdf英文原版2015)

    AngularJS makes web JavaScript web development less painful and more organized – it’s unsurprising that today it’s one of the most popular tools in web development. AngularJS by Example helps you ...

    Nodejs in action

    Node.js in Action is an example-driven tutorial that starts at square one and goes through all the features, techniques, and concepts needed to build production-quality Node applications. First it ...

    plug-In PHP- 100 Power Solutions

    For example, here’s the complete list of plug-ins which, while comprehensive, simply doesn't do justice to the depth and breadth of help, information, and practical code provided in this book: ...

    Packt.Publishing.CakePHP.Application.Development.Jun.2008

    One simple example: the minLength validation option was misspelled everywhere (as "minLenght") -- in code examples, in body copy, etc. And that's just one example. It's obvious that the examples in ...

    Learning.Underscore.js.178439381

    Underscore.js is one of the most popular modern JavaScript libraries used for functional programming. It can be used as a base for building complex JavaScript applications in a sustainable manner and ...

    Kotlin Blueprints-Packt Publishing(2017).epub

    This chapter shows how one can have the best of both worlds by doing the coding in Kotlin and, then, transpiling the code to JavaScript so that it works with the browsers seamlessly. The example that...

Global site tag (gtag.js) - Google Analytics