`
jj7jj7jj
  • 浏览: 50040 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

with(){} 的用法(javascript忍者的秘密) 【转】

阅读更多
     with语句也是一个功能强大的特性,但是它常常不能被正确的理解。它允许你把一个对象的所有属性放到with语句所指定的作用域中,这样这些属性就可以想平常的JavaScript变量被使用。理解with语句是如何工作的,在你开发中会带来很大的好处。



JavaScript中with(){}语句是如何工作的
让我们首先通过一个小例子来看看with(){}语句的基本用法:

var use = "other";
var katana = {
	isSharp: true,
	use: function(){
	    this.isSharp = !!this.isSharp;
	}
};
	with ( katana ) {
	//assert( true, "You can still call outside methods." );
	
	    isSharp = false;
	    use();
	    alert(use!='other');//true
	    alert(this);//window Object
	    //assert( use != "other", "Use is a function, from the katana object." );
	    //assert( this != katana, "this isn't changed - it keeps its original value" );
	}
	alert(typeof isSharp);//undefined
	alert(katana.isSharp);//false


从这个例子我们来总结一下with的基本用法:



1.在with(){}语句中,你可以直接使用with指定的对象的变量和方法。

2.如果外部存在和with指定的对象的变量同名的属性,那么with指定对象中的属性会覆盖其他同名的属性。

3.this指定的是katana的外部作用域。



那么我们能否在with(){}语句中添加一些属性和方法呢?来看一段代码:

	
var katana = {
    isSharp: true,
    use: function(){
        this.isSharp = !!this.isSharp;
    }
};
with ( katana ) {
    isSharp = false;
    cut = function(){
        isSharp = false;
    };
}
alert(katana.cut);//undefined
alert(cut);


从上面的代码我们可以发现:



1.在with语句中只能使用和更改对象已有属性,不能为对象添加新的属性

2.如果为对象添加新的属性,新添加的属性会作为全局对象的属性,而不是with指定对象的属性。

JavaScript中如何使用with(){}语句
我们主要通过一些著名的JavaScript库的示例代码来看看with(){}如何使用:



1.Prototype库中使用with(){}的情况。

Object.extend(String.prototype.escapeHTML, {
    div: document.createElement('div'),
    text: document.createTextNode('')
});
with (String.prototype.escapeHTML) div.appendChild(text);


下面是base2库中使用with的情况:

with (document.body.style) {
   backgroundRepeat = "no-repeat";
   backgroundImage = "url(http://ie7-js.googlecode.com/svn/trunk/lib/blank.gif)";
   backgroundAttachment = "fixed";
}


base2中另外的一中情况:
with (document.body.style) {
    backgroundRepeat = "no-repeat";
    backgroundImage = "url(http://ie7-js.googlecode.com/svn/trunk/lib/blank.gif)";
    backgroundAttachment = "fixed";
}


base2中另外的一中情况:
var Rect = Base.extend({
      constructor: function(left, top, width, height) {
      this.left = left;
      this.top = top;
      this.width = width;
      this.height = height;
      this.right = left + width;
      this.bottom = top + height;
   },
   contains: function(x, y) {
       with (this) return x >= left && x <= right && y >= top && y <= bottom;
},
   toString: function() {
       with (this) return [left, top, width, height].join(",");
   }
});


Firebug firefox extension中使用with(){}的情况

const evalScriptPre = "with (.vars) { with (.api) { with (.userVars) { with (window) {
     const evalScriptPost = "}}}}";
with ( obj ) { with ( window ) { ... } }


2.导入命名空间的时候使用如下
YAHOO.util.Event.on(
[YAHOO.util.Dom.get('item'), YAHOO.util.Dom.get('otheritem')],
'click', function(){
    YAHOO.util.Dom.setStyle(this,'color','#c00');
}
);
with ( YAHOO.util.Dom ) {
   YAHOO.util.Event.on([get('item'), get('otheritem')], 'click', function(){
   setStyle(this,'color','#c00');
});


第二个代码是不是简单了很多。

3.净化面向对象的代码,使用如下方式编写面向对象的代码。
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;
    };
  }
}


从上面的代码我们可以发现一下三点:

1.私有数据和共有数据是的定义是不一样的

2.由于使用with(this){}使得访问共有数据和私有数据是一样的

3.方法的的定义和变量的定义相似,共有方法必须使用this前缀,但是访问共有方法的时候和私有方法是一样的,由于使用with(this){}

原文地址:
http://blog.csdn.net/slalx/article/details/4025007
分享到:
评论

相关推荐

    Secrets Of The JavaScript Ninja

    本书面向已经具备一定JavaScript基础的开发者,旨在帮助他们提升技能至更高的层次,成为真正的“JavaScript忍者”。 #### 二、本书结构概述 本书分为三个部分:准备训练、学徒训练以及忍者训练。每一部分都涵盖了...

    Simple Fruit Ninja Game using JavaScript with Free Source.zip

    《使用JavaScript实现简易水果忍者游戏》 在编程领域,JavaScript是一种广泛应用于网页和网络应用开发的脚本语言。这个项目“Simple Fruit Ninja Game using JavaScript”提供了一个免费的源代码,让我们有机会深入...

    Secrets of the JavaScript Ninja(电子书,PDF)

    - **第10章:with语句** – 分析了`with`语句的特点及其使用场合。 - **第11章:跨浏览器策略开发** – 提供了一系列跨浏览器兼容性的最佳实践。 - **第12章:属性、特性和CSS的处理** – 讲解了如何处理HTML元素的...

    [JQuery菜鸟到忍者].Sitepoint.jQuery.Novice.to.Ninja.Feb.2010.pdf

    - **内容**:介绍了如何使用jQuery选择DOM元素、修改样式以及增强页面功能的方法。 - **重点**:详细讲解了jQuery提供的选择器及其用法,例如类选择器、ID选择器等,并教授了如何利用这些选择器来操作页面元素。 **...

    JQuery 菜鸟到忍者(jQuery Novice to Ninja)

    1. **Falling in Love with jQuery**(爱上jQuery):介绍jQuery的基本概念和发展历史,以及为什么选择使用jQuery进行网页开发。 2. **Selecting, Decorating, and Enhancing**(选择、装饰与增强):讲解如何使用...

    Become a ninja with Angular (2023-06-14) (Ninja Squad) (Z-Library).pdf

    Become a ninja with Angular需要具备扎实的JavaScript基础知识、ECMAScript 2015+的特性、TypeScript的使用、Angular框架的设计模式和功能等。只有具备这些知识,才能真正地Become a ninja with Angular。 ...

    SecretsOfJavaScriptNinja

    Javascript忍者秘术精要翻译自Secrets of Javascript Ninja,摘要其中最精妙的部分进行翻译Part 23 Functions are fundamental (函数是基础)4 Wielding functions (挥舞函数)6 Object-orientation with prototypes ...

    ninja-learning-app:学习忍者框架

    **忍者框架学习指南** 忍者框架(Ninja Framework)是一款专为Java开发的轻量级Web框架,它提供了一种高效、简洁的方式来构建现代化的Web应用。本指南将深入探讨Ninja框架的核心概念,帮助你快速掌握这个强大的工具...

Global site tag (gtag.js) - Google Analytics