search
HomeWeb Front-endH5 Tutorial教你如何塑造JavaScript牛逼形象

       如何写JavaScript才能逼格更高呢?怎样才能组织JavaScript才能让别人一眼看出你不简单呢?是否很期待别人在看完你的代码之后感叹一句“原来还可以这样写”呢?下面列出一些在JavaScript时的装逼技巧。

1. 匿名函数的N种写法

       你知道“茴”的四种写法吗?ε=(・д・`*)ハァ… 扯淡,但你或许不知道匿名函数的好几种写法。一般情况下写匿名函数是这样的:

(function(){})();

 但下面几种写法也是可以的:

!function(){}();
+function(){}();
-function(){}();
~function(){}();
~(function(){})();
void function(){}();
(function(){}());
复制代码

   其实细看可以看出规律,因为+-!~这些具有极高的优先级,所以右边的函数声明加上括号的部分(实际上就是函数执行的写法)就直接执行了。当然,这样的写法,没有什么区别,纯粹看装逼程度。

2. 另外一种undefined

       从来不需要声明一个变量的值是undefined,因为JavaScript会自动把一个未赋值的变量置为undefined。所有如果你在代码里这么写,会被鄙视的:

var data = undefined;

   但是如果你就是强迫症发作,一定要再声明一个暂时没有值的变量的时候赋上一个undefined。那你可以考虑这么做:


  1. var data = void 0; // undefined

复制代码       void在JavaScript中是一个操作符,对传入的操作不执行并且返回undefined。void后面可以跟()来用,例如void(0),看起来是不是很熟悉?没错,在HTML里阻止带href的默认点击操作时,都喜欢把href写成javascript:void(0),实际上也是依靠void操作不执行的意思。

       当然,除了出于装逼的原因外,实际用途上不太赞成使用void,因为void的出现是为了兼容早起ECMAScript标准中没有undefined属性。void 0的写法让代码晦涩难懂。

3. 抛弃你的if和else

       当JS代码里有大量的条件逻辑判断时,那代码看起来多可怕:


if () {
    // ...
} else if () {
    // ...
} else if () {
    // ...
} else {
    // ...
}
复制代码
     不用我说你都猜到用什么语法来简化if-else了。没错,用||和&&,很简单的原理就不用说啦。值得一提的是,有时候用!!操作符也能简化if-else模式。例如这样:
// 普通的if-else模式
var isValid = false;
if (value && value !== 'error') {
    isValid = true;
}
// 使用!!符号
var isValid = !!(value && value !== 'error');
复制代码

“!”是取反操作,两个“!”自然是负负得正了。

4. 不加分号

       关于JavaScript要不要加分号的争论已经吵了好几年。Google的JavaScript语法指南告诉我们要加分号,很多JavaScript语法书籍也告诉我们加上分号更安全。然而,分号加不加,全靠个人对代码的写法,你确信写得足够安全的话,不加分号显得更加高大上。

5. 赶上ES6的早班车

       ES6即将在年底正式发布,赶时髦的开发者们,赶快在自己的代码里用起来。用上module声明,写写class,捣鼓一下Map,这些都会让你的代码逼格更高。神马?你都不会用?那也好歹在代码头部加上一个ES5的”use strict”;呀。

6. 添加AMD模块支持

       给你写的代码声明一下AMD模块规范,这样别人就可以直接通过AMD的规范来加载你的模块了,如果别人没有通过规范来加载你的模块,你也可以优雅地返回一个常规的全局对象。来看看jQueryUI的写法:


(function( factory ) {
    if ( typeof define === "function" && define.amd ) {
        // AMD. Register as an anonymous module.
        define( [ "jquery" ], factory );
    } else {
        // Browser globals
        factory( jQuery );
    }
}(function( $ ) {
    // 这里放模块代码
    return $.widget;
}));
复制代码
    就用它来包裹你的实际代码吧,保证别人一看代码就知道你是个专业的开发者。

    7. Function构造函数

           很多JavaScript教程都告诉我们,不要直接用内置对象的构造函数来创建基本变量,例如var arr = new Array(2); 的写法就应该用var arr = [1, 2];的写法来取代。但是,Function构造函数(注意是大写的Function)有点特别。Function构造函数接受的参数中,第一个是要传入的参数名,第二个是函数内的代码(用字符串来表示)。


  1. var f = new Function('a', 'alert(a)'); f('test'); // 将会弹出窗口显示test

复制代码       或许大家疑惑了,你这样绕着写,跟function f(a) {alert(a);}比有什么好处呢?
事实上在某种情况下是有好处的,比如不能用eval的时候,你需要传入字符串内容来创建一个函数的时候。在一些JavaScript模板语言的解析,和字符串转换json对象的时候比较实用。

8. 用原生Dom接口不用jQuery

       一个傲娇的前端工程师是不需要jQuery的,前提是你经得起折腾。实际上,几乎所有的jQuery方法都可以用同样的Dom原生接口来实现,因为这货本来就是用原生接口实现的嘛,哈哈。怎样做到不用jQuery(也叫jQuery-free)呢?阮老师的博文《如何做到 jQuery-free?》 给我们很好的讲解了做法。依赖于querySelector和querySelectorAll这两个现代浏览器的接口,可以实现跟jQuery同样方便和同样效率的Dom查找,而且其他的类似Ajax和CSS的接口同样也可以把原生方法做一些兼容方面的包装即可做到jQuery-free。

总结

       上述所有的JavaScript装逼写法,一些是为了程序易懂或者效率提高的语法糖,这样的做法是比较可取的,比如前面所说的省略if-else的做法;而有些写法则容易造成代码晦涩难懂或者效率偏低,例如上面说的void 0的写法,实际上不可取。JavaScript语法上灵活,让大家对同一个功能有很多种不同的写法,写法上的优化是对程序结构和代码维护有很大帮助的。所以,装逼得装得好看。

以上就是教你如何塑造JavaScript牛逼形象的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.