Home Web Front-end JS Tutorial Detailed explanation of alternative writing methods of JavaScript_javascript skills

Detailed explanation of alternative writing methods of JavaScript_javascript skills

May 16, 2016 pm 03:06 PM

JavaScript 是屬於網路的腳本語言!

JavaScript 被數百萬計的網頁用來改進設計、驗證表單、偵測瀏覽器、建立cookies,以及更多的應用程式。

JavaScript 是因特網路上最受歡迎的腳本語言。

JavaScript 很容易使用!你一定會喜歡它的!

JavaScript一種解釋型的腳本語言,語法靈活,讓不同的人對同一個功能有很多種不同的寫法。怎樣組織JavaScript程式碼才能讓別人一眼看出你不簡單呢?是否很期待別人看完你的程式碼後感嘆一句「原來還可以這樣寫」呢?

匿名函數的N種寫法

Js的匿名函數是未申明函數名的自執行函數,格式如下:

(function(){})();
Copy after login

實際上在專案上我們常常在前面加上「;」:

;function(){}();
Copy after login

因為Js的語法是可以省略分號的,但是這種機制也會導致意外的錯誤。為了避免程式碼上線後合併壓縮成一個檔案造成語法錯誤,所以加上「;」可以避免未知錯誤。

但有時候我們看見別人的函式庫或是外掛裡面會這樣寫匿名函數:

+function(){}();
Copy after login

「+」在這裡是運算符,運算符具有極高的優先權,所以右邊的函數宣告加上括號的部分(其實就是函數執行的寫法)就直接執行了。其實不只前面可以是「+」號,「-」、「!」、「~」、「++」等運算子皆可。這裡只是做擴展介紹,具體用哪一種寫法看團隊統一規範。

拋棄Math.ceil()和Math.floor取整

也許在別的程式碼中看過這兩種符號~~和|0,直接看運行結果:

>> var a1 = 1.23
>> ~~a1
1
>> var a2 = 2.345
>> a2|0
2
>> var a3 = -3.45
>> ~~a3
-3
>> var a4 = -4.5
>> a4|0
-4
Copy after login

註明下,這種寫法不是原創,只是引用過來分析和說明下這種另類的寫法。簡單解釋,~是位元取反的運算符,可以將浮點數透過捨去小數點後面的所有位元來轉換為整數。正整數可轉換為無符號的十六進位值。然後再取反一次(~~)負負得正,就得到原來的整數。就是這麼任性不愛調方法,你說算不算也是一種優化。

注意:如果需要做嚴格的四捨五入運算就要慎用此方法,那就還是得用Math函數。

if和else也不是唯一

用if-else的條件判斷是很清晰的邏輯,在處理資料量不大情況下看起就不是很簡潔:

if (a===1) { //此处强烈建议用严格等于符号“===”,不会进行类型转换
a=2
} else if (a===3) {
a=4
} else {
a=5
}
Copy after login

看看用||和&&給程式碼瘦身後:

((a===1)&&(true,a=2))||((a===3)&&(true,a=4))||(a=5)
Copy after login

一行就搞定,瘦身成功。 ||和&&,很簡單的原理就不用說啦,裡面用到逗號運算符還不容易理解,可以繼續換成三元運算符:

(a===1 )? a=2:( (a===3) ? (a=4) : (a=5) )
Copy after login

這種寫法看起來結構是夠簡化,但別人看你的程式碼會有點吃力。

用toString取代煩人的字串拼接DOM結構

如果要動態產生一個dom結構一般我們是這樣實現的 :

var template = "<div>" 
+ "<h2>{title}</h2>"
+ "<div class='content' yAttr=''>{content}</div>"
+ "</div>"
Copy after login

如果再增加各種屬性和參數進去,大、小引號混亂很容易報錯。然而ES6提供了Template String幫我們解決了這個問題,你可以這樣寫:

var template = <div> 
<h2>{title}</h2> 
<div class='content' yAttr=''>{content}</div> 
</div>
Copy after login

 可問題是ES6現在還沒正式來啊…不怕,function.toString來解決我們青黃不接時的尷尬:

var rComment = /\/\*([\s\S]*&#63;)\*\//;
// multiply string 
function ms(fn){ 
return fn.toString().match(rComment)[1]
}; 
ms(function(){/* 
<div> 
<h2>{title}</h2> 
<div class='content' yAttr=''>{content}</div> 
</div> */
})
Copy after login

這裡的輸出和前面的字串輸出一樣一樣滴,前端程式猿們只需要專注在自己的dom結構上就好了。

新增AMD模組支持,提示代碼B格

給你寫的程式碼聲明一下AMD(非同步模組定義,Asynchronous Module Definition)模組規範,這樣別人就可以直接透過AMD的規範來載入你的模組了,如果別人沒有透過規範來載入你的模組,你也可以優雅地回傳一個常規的全域物件。來看看jQueryUI的寫法:

(function( factory ) { 
if ( typeof define === "function" && define.amd ) { 
// AMD模式。且依赖"jQuery"这个插件 
define( [ "jquery" ], factory ); } 
else { 
// 浏览器全局模式 
factory( jQuery ); 
} 
}(function( $ ) { 
// 这里放模块代码 
return $.widget; 
}));
Copy after login

改成AMD模組的結構,讓你的程式碼更適合瀏覽器端載入腳本依賴,按照這個格式來寫程式碼,保證別人一看程式碼就知道你是個專業的開發者。

繼承最優法

JavaScript的彈性,大大小小的繼承方式有十餘種之多。每種寫法優缺點各異,各家方法不一一列舉,舉個常用的繼承方法為例,原型繼承:

function Parent() {}
function Child() {}
Child.prototype = Parent.prototype
Child.prototype.constructor = Child ;
Copy after login

这种这种方法实际上是将Child.prototype和Parent.prototype中保存的指针指向了同一个对象,所以子对象原型中扩展一些属性以便之后继续继承的话,父对象的原型也会被改写。所以为了解决这个问题,尝试借用一个临时构造器的写法:

function Empty(){}
Empty.prototype = Parent.prototype;
Child.prototype = new Empty();
Child.prototype.constructor = Child;
Copy after login

这样父对象的自身属性和原型方法得到保护。“最优”有点夸大,但是是相比较而言的。相信每个人都有自己的写法,还有借用call和apply实现属性继承的优缺点,篇幅有限不一一介绍。

总结

上述所有的JavaScript的另类写法,一些是为了程序易懂或者效率提高的语法糖,这样的做法是比较可取的,比如前面所说的省略if-else的做法。一些是为了提升我们代码的兼容性和性能,比如AMD和继承的方式。……本人菜鸟一枚,上述内容肯定还有不全和没解释透彻的地方以后再补充。

以上内容是针对JavaScript的另类写法的相关介绍,希望对大家有所帮助!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles