金牛女跟什么星座最配| 下巴长痘什么原因| 泡奶粉用什么水最好| 路人皆知的上一句歇后语是什么| 咳嗽一直不好什么原因| 羊宝是什么| 牙疼吃什么食物| 热痱子长什么样| 李子有什么功效与作用| 有缘人什么意思| 行政管理是做什么的| 壁虎怕什么| 三岁属什么生肖| 牙龈为什么会肿痛| 手机为什么突然关机| 红花有什么作用| 盐酸哌替啶是什么药| 导弹是什么意思| 寿眉茶属于什么茶| 湿疹用什么药效果好| a型血的人容易得什么病| 肺部挂什么科| 筋皮是什么肉| 桑榆是什么意思| 什么叫点映| 肚子疼吃什么消炎药| 甲状腺结节3类什么意思| 吃醪糟有什么好处| 歌声什么| 什么是蜘蛛痣图片| 鳄鱼的天敌是什么动物| 汉高祖叫什么名字| 阴阳怪气是什么意思| 甲胎蛋白是什么指标| 过敏擦什么药膏好得快| 手指甲软薄是缺什么| 脚浮肿是什么原因引起的| 眼睛发黑是什么原因引起的| 血压低什么症状| 梦见螃蟹是什么预兆| 送礼送什么烟比较好| 女人的逼是什么意思| 吃竹笋有什么好处和坏处| 喝白酒有什么好处| 气胸是什么症状| 荷尔蒙是什么东西| 南岳什么山| 两个马念什么| 颈动脉挂什么科| 绝倒是什么意思| 梦见儿子小时候是什么意思| 同床出血什么原因呢| 压马路什么意思| 有利有弊是什么意思| 男人小腹疼痛是什么原因| 天珠是什么材质| 脚冰凉是什么原因| 肛门下坠是什么原因| 脱脂牛奶适合什么人喝| 番薯是什么意思| 舌苔厚黄是什么病| 禅心是什么意思| 金字塔里面有什么| 钠对人体有什么作用| 抽烟为什么会头晕| 什么猫最贵| 冠心病吃什么药好| 醋粉是什么做的| 大马士革是什么意思| 迪化是什么意思| 吃了避孕药不能吃什么东西| 明天属相是什么生肖| 大黄是什么药材| cba什么意思| 肾虚吃什么东西补得快| 雪菊有什么功效| 本科毕业证是什么颜色| 奇花异草的异是什么意思| 晚上吃什么饭| 早搏是什么感觉| 瘢痕子宫什么意思| 低落是什么意思| 马英九属什么| 高频听力损失意味什么| a型血和什么血型生出o型血| _什么字| 小产吃什么好恢复营养| 杨柳代表什么生肖| 高脂血症是什么意思| 蝗虫用什么呼吸| 手足口是什么| 蕾丝边是什么意思| 腌鱼放什么调料| 什么除湿气效果最好| 色弱什么意思| 骆驼奶有什么功效| 彩超无回声是什么意思| 田螺吃什么食物| 什么花是蓝色的| 男人吃逍遥丸治什么病| 左边头疼是什么原因| 闭口粉刺是什么原因引起的| 什么地唱| 女人喝黄芪有什么好处| 今天什么生肖冲什么生肖| 洗钱是什么意思| 里字五行属什么| 牙疼能吃什么食物| 印度是什么人种| 摩羯座跟什么星座最配| 钙化淋巴结是什么意思| 苹果什么季节成熟| 专科女生学什么专业好| 中国的国果是什么| 97属什么| 6541是什么药| 荣誉的誉是什么意思| 平行班是什么意思| 主动脉硬化什么意思| 一会硬一会软什么情况| sec是什么单位| 血压高吃什么药最好| 减肥什么方法有效| 封建社会是什么意思| 指鹿为马指什么生肖| 一颗颗什么| 帝加口念什么| 胃下垂吃什么药最好| 大便拉水是什么原因| 泡鲁达是什么| 排卵期出血是什么样的| 一个月来两次大姨妈是什么原因| 念珠菌性阴道炎用什么药| 晨尿泡沫多是什么原因| 坐飞机什么东西不能带| 正月初九是什么星座| 此情可待什么意思| 脸上白了一小块是什么原因| 白带清洁度lll度是什么意思| ip是什么意思| 脾肾两虚吃什么中成药| 病案号是什么意思| 甘油三酯高吃什么药最好| 潜阳是什么意思| 后背沉重感是什么原因引起的| 草朋刀是什么字| 晚上胃疼是什么原因| gift是什么意思| 白腊金是什么意思| 牛仔是什么面料| 黄水晶五行属什么| 肝肾功能挂什么科| 麦冬的功效与作用是什么| 字什么意思| 不是一路人是什么意思| 慢性咽炎吃什么药好得快能根治| dell是什么牌子的电脑| 疾苦的疾是什么意思| 脂溢性皮炎是什么原因引起的| 董酒是什么香型| 生小孩需要准备什么| 1927年属什么生肖| 阴虱卵长什么样图片| 什么光| 去港澳旅游需要什么证件| 嘴角长水泡是什么原因| 性质是什么| 臀推是什么意思| 京五行属什么| 皮肤瘙痒是什么原因| 女人梦见掉牙齿是什么征兆| 什么是态度| 梧桐树的叶子像什么| 鲜卑人是现在的什么人| 喝酸梅汤有什么好处| 扁桃体发炎吃什么消炎药| 安慰的意思是什么| 系统性红斑狼疮不能吃什么| 雨渐耳符咒有什么用| 肥胖纹什么样子| 蔡司是什么| 参天大树什么意思| 手上的三条线分别代表什么| 感冒低烧吃什么药| 县级干部是什么级别| 秀恩爱是什么意思| cpk是什么意思| 容颜是什么意思| 感冒发烧吃什么饭菜好| 精子是什么味道| 经常熬夜喝什么汤好| 裙带菜不能和什么一起吃| 肌钙蛋白高是什么意思| 北上广深是什么意思| 为什么会打哈欠| 护肝养肝吃什么好| 所剩无几是什么意思| 什么是疤痕增生| 孩子营养不良吃什么| 胸闷心慌是什么病| 脚干脚裂用什么药| 杰瑞是什么品种的老鼠| 脚肿挂什么科室| 普贤菩萨的坐骑是什么| 普外科是什么科| 无名指戴戒指代表什么| 布洛芬什么时候起效| 头皮发麻是什么原因| 粉墙用什么| 月经推迟7天是什么原因| 产褥热是什么病| 筋膜炎吃什么药最有效| 白带有点黄是什么原因| 5.29是什么星座| 天下之奇是什么生肖| 失眠是什么原因引起的| 一般什么人戴江诗丹顿| 前呼后拥是什么意思| 考教师资格证需要什么条件| 女命七杀代表什么| 1206是什么星座| 社保断交有什么影响| 红色代表什么| 人为什么会长痔疮| 7月7日是什么星座| qh是什么意思| 绯色是什么颜色| 白癜风是什么原因引起的| oink是什么意思| 多喝白开水有什么好处| 985和211是什么意思| 脱口秀是什么| 睡觉天天做梦是什么原因| 阴道炎用什么药| 白炽灯是什么灯| 骨钙素是什么| 爱屋及乌是什么意思| 仓鼠吃什么蔬菜| 阴囊潮湿挂什么科| 为什么你| 心悸症状是什么感觉| 扁桃体发炎咳嗽吃什么药效果好| 2001年属什么生肖| 果腹是什么意思| 蛏子是什么| 献血后吃什么| 狼吞虎咽什么意思| he是什么气体| 骟是什么意思| 甲状腺手术后有什么后遗症| 林彪什么时候死的| atp是什么| mt是什么| 医院建档是什么意思| 党内警告处分有什么影响| 割包皮有什么好处| 痘坑用什么药膏最有效| 什么洗面奶祛痘| 大马猴是什么意思| 蛋白粉什么味道| 不以为然是什么意思| 梗米是什么米| 神戳戳是什么意思| 一花一世界下一句是什么| 百度

6 Advanced JavaScript Techniques You Should Know

6 Advanced JavaScript Techniques You Should Know

There have been a number of articles published over the years that discuss best practices techniques for JavaScript. I thought I would go a little bit beyond the scope of those articles and outline a number of advanced techniques and practices that I have personally used or read about that could be invaluable in certain circumstances.

This article doesn’t necessarily cover every detail of the methods I’m describing, but provides an overview, along with code examples, of some practical JavaScript coding techniques.

1. Closures to Extend Variable Scope

Closures in JavaScript are a fairly straightforward concept, and have been discussed online in a number of in-depth articles. The fact that they are straightforward doesn’t necessarily mean they’re simple however, as seen by the extensive articles that cover the subject.

Simply put, closures allow variable scope to be extended past the common scope restrictions of functions. I like the way Jeremy Keith describes closures in his bookBulletproof Ajax:

“Think of closures as a kind of regional scope: broader than local but not as broad as global.”

To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent function’s scope. This comes in handy when creating methods and properties in object oriented scripts. Here is a simple example that demonstrates the use of a closure:

function myObject() {
  this.property1 = "value1";
  this.property2 = "value2";
  var newValue = this.property1;
  this.performMethod = function() {
    myMethodValue = newValue;
    return myMethodValue;
  };
  }
  var myObjectInstance = new myObject();
  alert(myObjectInstance.performMethod());

The key portions of the script are the nested anonymous function are highlighted in green and the method call in the?alert function (last line). Because the method in the alert is actually calling a nested function, that method is able to read the value of the variable called?newValue, even thought that variable is not within the scope of the anonymous function, or method.

Developers use closures all the time, probably unknowingly, since a closure is created any time an anonymous function is nested inside another function and utilizes variables from the parent function’s scope. The power of the closure is revealed when that method (the inner function) is called, and values that normally wouldn’t be accessible are within “regional” scope and are thus able to be used as any other value.

See the references below for some deeper explanations of closures and their relation to scope. I also highly recommend you pick up a good advanced JavaScript book that offers a good discussion of the concepts associated with closures.

Further Reading

2. Object Literals to Pass Optional Arguments

Here is a handy coding tip to keep in mind when dealing with functions that can accept a large number of optional arguments. Instead of passing the large number of arguments in the conventional fashion, which could unnecessarily complicate the function, you can pass just one argument which ends up being a collection of arguments declared in an object literal.

Let’s look, first of all, at how we might do this in the typical manner, so we can see the contrast:

function showStatistics(name, team, position, average, homeruns, rbi) {
  document.write("<p><strong>Name:</strong> " + arguments[0] + "<br />");
  document.write("<strong>Team:</strong> " + arguments[1] + "<br />");

  if (typeof arguments[2] === "string") {
    document.write("<strong>Position:</strong> " + position + "<br />");
  }
  if (typeof arguments[3] === "number") {
    document.write("<strong>Batting Average:</strong> " + average + "<br />");
  }
  if (typeof arguments[4] === "number") {
    document.write("<strong>Home Runs:</strong> " + homeruns + "<br />");
  }
  if (typeof arguments[5] === "number") {
    document.write("<strong>Runs Batted In:</strong> " + rbi + "</p>");
  }
}
showStatistics("Mark Teixeira");
showStatistics("Mark Teixeira", "New York Yankees");
showStatistics("Mark Teixeira", "New York Yankees", "1st Base", .284, 32, 101);

The function above can take up to 6 arguments. The first two arguments are mandatory, so inside the function, we don’t check for their existence. The last 4 arguments are not mandatory, so we only display their values if they exist.

We call the function 3 different times (last 3 lines), with different numbers of arguments each time. You can see that if the number of passed arguments was in the dozens, or more, the code could look a little messy, and would be harder to maintain, or read.

Now let’s look at the same code using object literals to pass the arguments:

function showStatistics(args) {
  document.write("<p><strong>Name:</strong> " + args.name + "<br />");
  document.write("<strong>Team:</strong> " + args.team + "<br />");
  if (typeof args.position === "string") {
    document.write("<strong>Position:</strong> " + args.position + "<br />");
  }
  if (typeof args.average === "number") {
    document.write("<strong>Average:</strong> " + args.average + "<br />");
  }
  if (typeof args.homeruns === "number") {
    document.write("<strong>Home Runs:</strong> " + args.homeruns + "<br />");
  }
  if (typeof args.rbi === "number") {
    document.write("<strong>Runs Batted In:</strong> " + args.rbi + "</p>");
  }
}

showStatistics({
  name: "Mark Teixeira"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees",
  position: "1st Base",
  average: .284,
  homeruns: 32,
  rbi: 101
});

Technically, this second method of passing the arguments might require a little bit more code, but with a large collection of arguments, there are a few advantages.

First, the function itself is simplified because it accepts only one argument (args), which is a collection of all the values passed from the object literal (name,?team,position, etc). Plus, the actual argument values are easy to read, and can easily be understood, updated, or modified, since the correlation between the values and the argument references are more direct.

If the function required only a small number of arguments, then this method would not be necessary, and might actually have the opposite effect. So, use this technique sparingly, and only in situations where you foresee the collection of arguments being hard to maintain over time.

Further Reading

3. Contextual Targeting of DOM Elements

There are sometimes instances where you need to traverse the DOM and gain access to a specific element, or group of elements, but due to certain restrictions, you may not have direct access to the elements via a CSS class name or ID in the HTML code. This might be because of user-generated content produced through a rich text editor, or dynamic content pulled from a database.

Whatever the case, it’s not impossible to access those unidentified DOM elements via JavaScript. Using what I call “contextual targeting”, you can gain access to, and modify, almost any element in the DOM. As long as you have a map of the general template that contains the element you want to target, you can access that element and manipulate it the same way you would an element that has a class name or ID.

Let’s create some basic HTML code that will serve as our example page:

<div id="header">
  <h1>Site Title</h1>
</div>
<div id="sidebar">
  <ul>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
  </ul>
</div>
<div id="content">
  <h2>Page Title</h2>
  <p><a href="#">Lorum Ipsum link here</a>. Pellentesque habitant morbi
     tristique senectus et netus et malesuada fames ac turpis egestas.
     Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
     ante. Donec eu libero sit amet quam egestas semper.
     Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
     Pellentesque habitant morbi tristique senectus et netus et malesuada
     fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
     ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
     egestas semper. Aenean ultricies mi vitae est. Mauris
     placerat eleifend leo.</p>
  <p><span style="color: red;">Pellentesque habitant morbi</span>
    tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum
    tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec
    eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
    feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit
    amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat
    eleifend leo.</p>
</div>
<div id="footer">
   <p>Copyright | <a href="#">contact</a> | <a href="#">policy</a> |
      <a href="#">privacy</a></p>
</div>

Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect them and manipulate them like this:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  // do something with the anchor tags here
}

If we wanted to target only the anchor tags in the footer, however, we would target them based on their context, or surrounding elements, like this:

var myFooterElement = document.getElementById("footer");
var myLinksInFooter = myFooterElement.getElementsByTagName("a");
for (i=0;i<myLinksInFooter.length;i++) {
  // do something with footer anchor tags here
}

The first line grabs a reference to the footer element. The second line collects all?<a>tags inside the footer. Then we loop through them and do what we want with them. Thus, they are accessible even though they are not grouped via class names.

You can accomplish the same thing by using node properties, as shown below.

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].parentNode.parentNode.id === "footer") {
    // do something with footer anchor tags here
  }
}

Similar code could be used to target the lone anchor tag inside the “content” section.

We could also limit our anchor tag search to include only tags that have the?hrefattribute set, so as to avoid finding any in-page links. We do this by using thegetAttribute method:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("href")) {
    // do something with the anchor tags here
  }
}

Finally, you’ll notice that there is a?<span> tag with an inline style. The inline style could have been generated through a content management system, so you may not have the ability to edit it directly. You can target all?<span> elements with inline styles like this:

var myLinkCollection = document.getElementsByTagName("span");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("style")) {
    // do something with all anchors that have inline styles
  }
}

The possibilities are endless with contextual targeting, and there are even more options available if you’re using a JavaScript library that normalizes browser differences and simplifies DOM manipulation.

Further Reading:

4. Using Namespaces to Prevent Conflicts

If you’re doing an extensive amount of raw JavaScript coding and suspect that additions could be made to the same pages you’re working on, you can prevent any future conflicts with your code by giving your code its own namespace.

Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names. And very likely, the conflict will occur “silently”, thus you may not be alerted to the issue immediately.

You can prevent all conflicts by creating a unique namespace. Let’s use theshowStatistics function to demonstrate how we can encapsulate code into its own namespace:

if (typeof MY == "undefined") {
  MY = new Object();
  MY.CUSTOM = new Object();
}

MY.CUSTOM.namespace = function() {
  function showStatistics(args) {
    document.write("<p><strong>Name:</strong> " + args.name + "<br />");
    document.write("<strong>Team:</strong> " + args.team + "<br />");
    if (typeof args.position === "string") {
      document.write("<strong>Position:</strong> " + args.position + "<br />");
    }
    if (typeof args.average === "number") {
      document.write("<strong>Average:</strong> " + args.average + "<br />");
    }
    if (typeof args.homeruns === "number") {
      document.write("<strong>Home Runs:</strong> " + args.homeruns + "<br />");
    }
    if (typeof args.rbi === "number") {
      document.write("<strong>Runs Batted In:</strong> " + args.rbi + "</p>");
    }
  }

  showStatistics({
    name: "Mark Teixeira",
    team: "New York Yankees",
    position: "1st Base",
    average: .284,
    homeruns: 32,
    rbi: 101
  });
}
MY.CUSTOM.namespace();

The first few lines create the namespace by checking to see if the “MY” object already exists. This object can be whatever you want it to be. Just pick a name that you don’t think will ever be used again. After the?MY object is created, we are then able to create the “CUSTOM” object as a property of the?MY object. Then our?namespacefunction becomes a method of the?MY.CUSTOM object. Keep in mind that “MY“, “CUSTOM” and “namespace” can each be your own custom names. I chose these for demonstration purposes. They could be?CHEESEBURGER.ONIONS.pickles if you want!

The?showStatistics function is exactly the same as in the example earlier that utilizes an object literal to pass in the values. But in this case, the entire function, including the object literal, is encapsulated inside?my.custom.namespace. The last line invokes the entire function using dot notation, and the function runs exactly the same as it normally would, except that it is protected from conflicting with another function called “showStatistics“.

Further Reading:

5. Hybrid Application Development

You can create powerful JavaScript applications if you use a combination of a JavaScript library and raw JavaScript code. Many JavaScript libraries are used to implement “pretty” animations and other customizable effects–sometimes via plugins– that often don’t require much to be added to them other than some custom values.

On the other hand, there may be situations where you’ll want to accomplish something specificly requested by a client. Maybe it’s something not available in a library and that requires extensive coding, possibly utilizing Ajax and a variety of DOM methods.

There is no point in reinventing the wheel. You can implement your favorite JavaScript library and take advantage of its simplified Ajax calls, DOM methods, and normalization of browser differences. Thus, you can have the advantages of the library, while still creating custom scripts that are specific to your project.

Leave a comment

Design a site like this with WordPress.com
Get started
胸口堵得慌是什么原因 射手座是什么星座 马超是什么生肖 组织部副部长是什么级别 牛奶和什么不能一起吃
万事如意是什么生肖 属蛇与什么属相相克 今年什么生肖 星期五右眼皮跳是什么预兆 腰穿是什么意思
阴茎硬不起吃什么药 口臭吃什么中成药 6月12是什么星座 早期复极是什么意思 什么什么似火
醋酸纤维是什么面料 头发爱出油是什么原因 生日吃什么 猴子怕什么 鸡内金是什么
体检前一天晚上吃什么hcv8jop4ns7r.cn 八段锦什么时候练最好onlinewuye.com 什么叫阵雨hcv7jop7ns3r.cn 看淋巴挂什么科室hcv9jop2ns9r.cn 发票抬头是什么bjhyzcsm.com
夏季风寒感冒吃什么药hcv9jop6ns3r.cn 手臂发麻是什么原因引起的hcv9jop8ns2r.cn 为什么乳头会疼hcv9jop6ns0r.cn 邮件号码是什么hcv9jop8ns2r.cn 办理公证需要什么材料hcv9jop0ns3r.cn
女性多吃什么滋补卵巢hcv8jop7ns2r.cn 星光是什么意思gangsutong.com 劳作是什么意思hcv7jop6ns3r.cn 孩子发烧挂什么科hcv9jop6ns4r.cn 菠萝为什么要用盐水泡hcv8jop3ns3r.cn
胡塞武装是什么hcv8jop3ns2r.cn 什么叫凤凰男hcv8jop6ns7r.cn lsp什么意思hcv8jop5ns1r.cn 奥倍健是什么药0297y7.com 湿阻病是什么病hcv9jop2ns9r.cn
百度