`

javascript closures and function contexts

阅读更多

Javascript has four kind of functions, namely 

  • global function 
  • constructor
  • prototype 
  • closure

I may be wrong about the types, but the rule of thumb is that the functions differs from each other in terms of how the 'this' pointer is determined.

 

another things that you might be aware is that , with the .call() and .apply() method, you can manipulate the context of a function. 

 

let's take an example. 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="../unit.js" type="text/javascript"></script>

</head>
    <style type="text/css" >
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>

<body>
<button id="test">click me!</button>

<script type="text/javascript">

  function trigger(elem, name) {
    elem[name]();
  }

  window.onload = function () {
    test("function context ", function () {

      var Button = {
        click: function () {
          this.clicked = true;
        }
      };

      var elem = document.getElementById("test");
      elem.addEventListener("click", Button.click, false);
      trigger(elem, "click");

      assert(elem.clicked, " The clicked property was accidently set on the element");
      elem.removeEventListener("click", Button.click, false);
    });


  };

</script>

<ul id="results" />
</body>
</html>

 

 

please be NOTED that the unit.js is a home-crafted test framework, which I will share in some other post. 

 

 

as you can see, if you run this test, when you click on the button, the button with id test will have its clicked proeprty set, which is not what we want, it happens because the 'this' inside of the click function is referring to whatever context the function currently has.

 

a revised way is like this: 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="../unit.js" type="text/javascript"></script>
    <script src="functioncontext.js" type="text/javascript"></script>
</head>
    <style type="text/css" >
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>

<body>
<button id="test">click me!</button>

<script type="text/javascript">

  function trigger(elem, name) {
    elem[name]();
  }

  window.onload = function () {

    test("function context 2", function () {

      var Button = {
        click: function () {
          this.clicked = true;
        }
      };

      var elem = document.getElementById("test");
      var eventhandler = bind(Button, "click");
      elem.addEventListener("click", eventhandler, false);
      trigger(elem, "click");
      assert(Button.clicked, "the clicked property was set on our object");
      elem.removeEventListener("click", eventhandler, false);
    });
  };

</script>

<ul id="results" />
</body>
</html>
 

 

the content of the "functioncontext.js" is like this 

 

 

function bind(context, name) {
  return function () {
    return context[name].apply(context, arguments);
  }
}
 

the key here is that we used the .call() funtion, which we can override the function context (affect what this binds to).

分享到:
评论

相关推荐

    secrets_of_javascript_closures.pdf

    secrets_of_javascript_closures.pdf

    Java Closures and Lambda(Apress,2015)

    Java Closures and Lambda introduces you to significant new changes to the Java language coming out of what is termed Project Lambda. These new changes make their debut in Java 8, and their highlight ...

    Apress - Java Closures and Lambda.2015

    ### Apress - Java Closures and Lambda (2015):关键知识点解析 #### 引言 本书《Apress - Java Closures and Lambda》聚焦于Java 8中的新特性——闭包(Closures)和Lambda表达式。这些新功能不仅为Java语言带来...

    Advanced JavaScript (closures,prototype,inheritance)

    JavaScript,作为一种广泛应用于Web开发的脚本语言,其高级特性如闭包(closures)、原型(prototype)和继承(inheritance)是理解其精髓的关键。本文将深入探讨这些概念,帮助开发者更好地掌握JavaScript的核心。 ...

    JavaScript Functional Programming for JavaScript Developers (PDF, EPUB, MOBI)

    The first module Mastering JavaScript, stress on practical aspects of Javascript development like—Functions and Closures, Runtime debugging techniques, project layout, events and DOM processing, ...

    Mastering.JavaScript.1785281348

    - Get familiar with the Functions and Closures of JavaScript - Explore Regular Expressions in JavaScript - Code using the powerful object-oriented feature in JavaScript - Test and debug your code ...

    Programming JavaScript Applications

    , AMD, Asynchronous Operations, Callbacks, Promises and Deferreds, Code Quality, Function Polymorphism, Function Scope, Hoisting and Closures, Functional Programming and Stateless Functions, ...

    深入理解JavaScript系列

    深入理解JavaScript系列(11):执行上下文(Execution Contexts) 深入理解JavaScript系列(12):变量对象(Variable Object) 深入理解JavaScript系列(13):This? Yes, this! 深入理解JavaScript系列(14)...

    深入理解JavaScript系列(.chm)

    深入理解JavaScript系列(11):执行上下文(Execution Contexts) 深入理解JavaScript系列(12):变量对象(Variable Object) 深入理解JavaScript系列(13):This Yes this 深入理解JavaScript系列(14):...

    Learning JavaScript Design Patterns 英文原版.js设计模式

    If you want to write ... If you’re familiar with concepts such as closures and prototypal inheritance, you’ll be able to determine why some patterns may be more suitable for your projects than others.

    javascript.the.definitive.guide.5th.2006(英文版)

    It documents every class, object, constructor, method, function, property, and constant defined by JavaScript 1.5 and ECMAScript version 3. Part IV is a reference for client-side JavaScript, ...

    Mastering JavaScript(PACKT,2016)

    Get familiar with the Functions and Closures of JavaScript Explore Regular Expressions in JavaScript Code using the powerful object-oriented feature in JavaScript Test and debug your code using ...

    JavaScript: Moving to ES2015

    Get a run through of the basic language constructs, Functions, and Closures of JavaScript Code using the powerful object-oriented feature in JavaScript Master DOM manipulation, cross-browser ...

    Javascript.Object.Oriented.Programming.pdf

    Chapter 2: Functions, Closures, And Modules Chapter 3: Data Structures And Manipulation Chapter 4: Object-Oriented Javascript Chapter 5: Javascript Patterns Chapter 6: Testing And Debugging Chapter 7:...

    Speaking JavaScript

    Variables: Scopes, Environments, and Closures Chapter 17. Objects and Inheritance Chapter 18. Arrays Chapter 19. Regular Expressions Chapter 20. Dates Chapter 21. Math Chapter 22. JSON Chapter 23. ...

    JavaScript权威指南(第五版).chm

    It documents every class, object, constructor, method, function, property, and constant defined by JavaScript 1.5 and ECMAScript version 3. Part IV is a reference for client-side JavaScript, ...

Global site tag (gtag.js) - Google Analytics