`

javascript the 'with' statement

阅读更多

The with() {} statement is meant to provide convenience. 

 

 

and there are some golden laws about the with() {} statement.

 

 

  1. it only use/assign existing properties
  2. it does not affect what is 'this'
  3. the scoped variable inside with statement take precedence over others with the same name
  4. it slows things down.,

let's first see some simple example that shows something about the with statement.

 

 

/**************************************
*@Summary
* this shows the simple use of with statement
*
* the key rule about the use of the statement is that it 
*   1. does not affect what is 'this' context. 
*   2. it does not help create properties that is not in the 'with' scoped variable. You can only use and assign existing properties in the with() {} statement
*   3. within the scope of the statement, the properties introduced by with(){} take precedence over the other variables.
*   4. and it slows things down (not sure where comes the extra overhead)
* @Usage:
*   
* @TODO:
* test it 
***************************************/

var use = "other";
var katana = {
  isSharp: true,
  use: function () {
    this.isSharp = !this.isSharp;
  }
};

//with (katana) {
//  assert(true, "you can still call outside mehtods.");

//  isSharp = false;

//  use();
//  // this illustrate the fact that local with variable take precedence
//  assert(use !== "other", "Use is a function, from the kantana object");

//  assert(this !== katana, "This isn't changed - it keeps its original value");
//}

// commentted out, to test it , copy the following code to the test html and do the test
//assert(typeof isSharp === "undefined", "Outside the with, the properties don't exist.");
//assert(katana.isSharp, "Verify that the method was used correctly in the with.");
 

and below is its test cases.

 

 

<!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="simplewith.js" type="text/javascript"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("with(){} doest not change what 'this' is. and it simplifies things", function () {
          with (katana) {
            assert(true, "you can still call outside mehtods.");

            isSharp = false;

            use();
            // this illustrate the fact that local with variable take precedence
            assert(use !== "other", "Use is a function, from the kantana object");

            assert(this !== katana, "This isn't changed - it keeps its original value");
          }

          assert(typeof issharp === "undefined", "outside the with, the properties don't exist.");
          assert(katana.isSharp, "verify that the method was used correctly in the with.");
        });

        test("you cannot access non-existing properties inside with(){} statement", function () {
          with (katana) {
            isSharp = false;
            cut = function () {
              isSharp = false;
            };
          }
          assert(!katana.cut, "The new cut property wasn't introduced here.");
          assert(this.cut, "It was made as a member variable to the anonymous function that contains the test instead.");
        });
      };
    
    </script>

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

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

 

also, with the 'with' statement, you can chang the way how the code is written to simulate some object-oriented javascript code.

 

 

/**************************************
*@Summary
* this shows how you can use the with statement to facilitate writting some OO like code. 
*
* the key rule about why the use of the statement has the advantage is that 
*   1.it introduce a local scope
*   2. you can have something like private and public, which is missing in non-with statement
*   3. you can access the private and public through names alike inside the with statement, but outside the visibility is different.
* @Usage:
*   
* @TODO:
* test it 
***************************************/

function Ninja(){with(this){
  // Private Information
  var cloaked = false;
  // Public property
  this.swings = 0;
  // Private Method
  function addSwing(){
    return ++swings;
  }
  // Public Methods
  this.swingSword = function(){
    cloak( false );
    return addSwing();
  };
  this.cloak = function (value) {
    return value != null ?
    cloaked = value :
    cloaked;
  };
} 
}

// below is the test code.
var ninja = new Ninja();
assert(!ninja.cloak(), "We start out uncloaked.");
assert(ninja.swings == 0, "And with no sword swings.");
assert(ninja.cloak(true), "Verify that the cloaking worked correctly.");
assert(ninja.swingSword() == 1, "Swing the sword, once.");
assert(!ninja.cloak(), "The ninja became uncloaked with the sword swing.");
 

 

分享到:
评论

相关推荐

    JavaScript in 10 Minutes

    "JavaScript in 10 Minutes" is a concise guide that aims to provide intermediate to advanced JavaScript developers with an overview of the language's unique features and nuances. This document is not ...

    javascript语言精粹(中英文版)

    The function Statement Versus the function Expression Section B.10. Typed Wrappers Section B.11. new Section B.12. void Appendix C. JSLint Section C.1. Undefined Variables and Functions Section...

    Windows 10 Development Recipes pdf 无水印 0分

    Each recipe includes a concise statement of the problem and the approach you should take in order to solve it. A full code solution is also given, along with an in-depth explanation, so you can build ...

    jdk1.8-windows版64位

    8. **Nashorn JavaScript Engine:** JDK 1.8 includes a built-in JavaScript engine called Nashorn, allowing Java developers to execute JavaScript code within the JVM and facilitate interoperation between...

    Windows.10.Development.Recipes

    Each recipe includes a concise statement of the problem and the approach you should take in order to solve it. A full code solution is also given, along with an in-depth explanation, so you can build ...

    QTP11补丁发布 - 支持IE9浏览器识别

    box for window.alert, window.confirm, and window.prompt statements in the JavaScript. The rest of the JavaScript will run. 3. When using a Web Add-in Extensibility-based Add-in, if the JavaScript ...

    ajax in prpc

    AJAX (Asynchronous JavaScript and XML) is a technique used for creating faster and more interactive web applications by exchanging data with a server behind the scenes and updating parts of a web ...

    java7帮助文档

    The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement; see Closing Connections in Processing SQL Statements. RowSet 1.1: The ...

    bookmarklets:ImportMyBankStatement.com JavaScript 书签

    然而,某些技术如CORS(跨源资源共享)或JSONP(JSON with Padding)可以帮助绕过这一限制,使书签能够与银行网站交互。 6. **存储与同步**:一旦数据被提取和处理,可能需要将其存储在浏览器的本地存储(如...

    python3.6.5参考手册 chm

    PEP 343: The ‘with’ statement Writing Context Managers The contextlib module PEP 366: Explicit Relative Imports From a Main Module PEP 370: Per-user site-packages Directory PEP 371: The ...

    Beginning Microsoft Visual CSharp 2008 Wiley Publishing(english)

    The goto Statement 106 Branching 107 Looping 115 Summary 127 Exercises 127 Chapter 5: More About Variables 130 Type Conversion 130 Complex Variable Types 140 String ...

    VA_X_Setup1940

    Fixed focus issue with the suggestion list that appears following "in" in a C# foreach statement. (case=73981) 10226 Surround With feature is no longer invokable within comments, string literals, and ...

    jdk1.7_80 window.64

    - **Scripting Language Support:** Improved integration with scripting languages like JavaScript, Ruby, and Python through the javax.script package. - **JSON Processing (JSR 353):** A standard API ...

    php.ini-development

    The directory from the --with-config-file-path compile time option, or the ; Windows directory (C:\windows or C:\winnt) ; See the PHP docs for more specific information. ; ...

    LotusDomino学习笔记(400页涵盖代理和公式使用)

    76. Web search with JavaScript 162 77. 如何防止他人使用旧id和旧口令访问Domino服务器 164 78. Fixing the Domino CheckBox Bug 165 79. Managing JavaScript "popup" windows 172 80. Quick, easy, foolproof ...

    Lotus Domino WEB详细 学习笔记

    76. Web search with JavaScript 162 77. 如何防止他人使用旧id和旧口令访问Domino服务器 164 78. Fixing the Domino CheckBox Bug 165 79. Managing JavaScript "popup" windows 172 80. Quick, easy, ...

    程序语言设计原理习题解答

    12.9 The Object Model of JavaScript 524 12.10 Implementation of Object-Oriented Constructs 527 Summary • Review Questions • Problem Set •Programming Exercises 530 Chapter 13 Concurrency ...

    it英语词汇(有例句)

    例如:“In Java, you define a class with the `class` keyword, like `public class Car { ... }`”。 4. **Database(数据库)** - 数据库是用来组织、存储和检索数据的系统。例如:“MySQL is a popular ...

    LotusDomino学习笔记.doc

    Web search with JavaScript - **搜索方法**: 展示如何使用JavaScript实现Web搜索功能。 #### 77. 如何防止他人使用旧id和旧口令访问Domino服务器 - **防止方法**: 通过定期更改密码策略和禁用旧ID来提高安全性。 ...

    50种避免,发现和修复ASP.NET性能问题的方法

    - **Reduce memory leaks dramatically with the “using” statement (利用“using”语句大幅减少内存泄漏)** - .NET中的`using`语句提供了一种优雅地管理资源的方式。它确保即使在发生异常的情况下,资源也能正确...

Global site tag (gtag.js) - Google Analytics