search
HomeWeb Front-endJS TutorialjQuery Theatrical Edition What you must know about javascript_jquery

一.摘要

本文是jQuery系列教程的剧场版, 即和jQuery这条主线无关, 主要介绍大家平时会忽略的一些javascript细节.  适合希望巩固javascript理论知识和基础知识的开发人员阅读.

 

二.前言

最近面试过一些人, 发现即使经验丰富的开发人员, 对于一些基础的理论和细节也常常会模糊. 写本文是因为就我自己而言第一次学习下面的内容时发现自己确实有所收获和感悟.  其实我们容易忽视的javascript的细节还有更多, 本文仅是冰山一角. 希望大家都能通过本文有所斩获.

 

三.Javascript面向对象

Javascript是一门面向对象的语言,  虽然很多书上都有讲解,但还是有很多初级开发者不了解. 

创建对象

ps: 以前写过一篇详细的创建对象的文章(原型方法, 工厂方法等)但是找不到了, 回头如果还能找到我再添加进来.下面仅仅简单介绍.

在C#里我们使用new关键字创建对象, 在javascript中也可以使用new关键字:

<SPAN class=kwrd>var</SPAN> objectA = <SPAN class=kwrd>new</SPAN> Object();

 

但是实际上"new"可以省略:

<SPAN class=kwrd>var</SPAN> objectA = Object();


但是我建议为了保持语法一直, 总是带着new关键字声明一个对象.

创建属性并赋值

在javascript中属性不需要声明, 在赋值时即自动创建:

objectA.name = <SPAN class=str>"my name"</SPAN>;

 

访问属性

一般我们使用"."来分层次的访问对象的属性:

alert(objectA.name);

 

嵌套属性

对象的属性同样可以是任何javascript对象:

<SPAN class=kwrd>var</SPAN> objectB = objectA;
objectB.other = objectA;
<SPAN class=rem>//此时下面三个值相当, 并且改变其中任何一个值其余两个值都改变</SPAN>
<SPAN class=rem></SPAN>objectA.name;
objectB.name;
objectB.other.name;

 

使用索引

如果objectA上有一个属性名称为"school.college", 那么我们没法通过"."访问,因为"objectA.school.college"语句是指寻找objectA的school属性对象的college属性.

这种情况我们需要通过索引设置和访问属性:

     objectA[<SPAN class=str>"school.college"</SPAN>] = <SPAN class=str>"BITI"</SPAN>;
     alert(objectA[<SPAN class=str>"school.college"</SPAN>]);

 

下面几个语句是等效的:

    objectA[<SPAN class=str>"school.college"</SPAN>] = <SPAN class=str>"BITI"</SPAN>;
    <SPAN class=kwrd>var</SPAN> key = <SPAN class=str>"school.college"</SPAN>
    alert(objectA[<SPAN class=str>"school.college"</SPAN>]);
    alert(objectA[<SPAN class=str>"school"</SPAN> + <SPAN class=str>"."</SPAN> + <SPAN class=str>"college"</SPAN>]);    
    alert(objectA[key]);

 

JSON 格式语法

JSON是指Javascript Object Notation, 即Javascript对象表示法.

我们可以用下面的语句声明一个对象,同时创建属性:

    <SPAN class=rem>//JSON</SPAN>
    <SPAN class=kwrd>var</SPAN> objectA = {
      name: <SPAN class=str>"myName"</SPAN>,
      age: 19,
      school:
      {
        college: <SPAN class=str>"大学"</SPAN>,
        <SPAN class=str>"high school"</SPAN>: <SPAN class=str>"高中"</SPAN> 
      },
      like:[<SPAN class=str>"睡觉"</SPAN>,<SPAN class=str>"C#"</SPAN>,<SPAN class=str>"还是睡觉"</SPAN>]
    }

JSON的语法格式是使用"{"和"}"表示一个对象,  使用"属性名称:值"的格式来创建属性, 多个属性用","隔开.

上例中school属性又是一个对象. like属性是一个数组. 使用JSON格式的字符串创建完对象后, 就可以用"."或者索引的形式访问属性:

objectA.school[<SPAN class=str>"high school"</SPAN>];
objectA.like[1];

静态方法与实例方法

静态方法是指不需要声明类的实例就可以使用的方法.

实例方法是指必须要先使用"new"关键字声明一个类的实例, 然后才可以通过此实例访问的方法.

    <SPAN class=kwrd>function</SPAN> staticClass() { }; <SPAN class=rem>//声明一个类</SPAN>
    staticClass.staticMethod = <SPAN class=kwrd>function</SPAN>() { alert(<SPAN class=str>"static method"</SPAN>) }; <SPAN class=rem>//创建一个静态方法</SPAN>
    staticClass.prototype.instanceMethod = <SPAN class=kwrd>function</SPAN>() { <SPAN class=str>"instance method"</SPAN> }; <SPAN class=rem>//创建一个实例方法</SPAN>
   

上面首先声明了一个类staticClass, 接着为其添加了一个静态方法staticMethod 和一个动态方法instanceMethod. 区别就在于添加动态方法要使用prototype原型属性.

对于静态方法可以直接调用:

staticClass.staticMethod();

但是动态方法不能直接调用:

staticClass.instanceMethod(); //语句错误, 无法运行.

 

需要首先实例化后才能调用:

    <SPAN class=kwrd>var</SPAN> instance = <SPAN class=kwrd>new</SPAN> staticClass();<SPAN class=rem>//首先实例化</SPAN>
    instance.instanceMethod(); //在实例上可以调用实例方法

 

四.全局对象是window属性


通常我们在<script>标签中声明一个全局变量, 这个变量可以供当前页面的任何方法使用:</script>

  <script type="text/javascript">
    <SPAN class=kwrd>var</SPAN> objectA = <SPAN class=kwrd>new</SPAN> Object();
  script>

然而我们还应该知道, 实际上全局变量objectA是创建在window对象上, 可以通过window对象访问到:

window.objectA

五.函数究竟是什么

我们都知道如何创建一个全局函数以及如何调用:

    <SPAN class=kwrd>function</SPAN> myMethod()
    {
      alert(<SPAN class=str>"Hello!"</SPAN>);
    }

    myMethod(); 

其实同全局对象一样, 使用function关键字创建的方法(也可以创建类)的名称, 实际上是为window对象创建了myMethod属性, 并且值是一个匿名方法, 上面的语句等同于:

    window.myMethod = <SPAN class=kwrd>function</SPAN>()
    {
      alert(<SPAN class=str>"Hello!"</SPAN>);
    }

无论使用哪种方式声明, 实际保存时都是使用函数名创建window对象的属性. 并且值只有函数体没有函数名称.

所以,下面三种声明方式是等效的:

    function myMethod()
    {
      alert("Hello!");
    }

    window.myMethod = <SPAN class=kwrd>function</SPAN>()
    {
      alert(<SPAN class=str>"Hello!"</SPAN>);
    }

    myMethod = function()
    {
      alert("Hello!");
    }

六."this"究竟是什么

在C#中,this变量通常指类的当前实例. 在javascript则不同, javascript中的"this"是函数上下文,不是由声明决定,而是由如何调用决定.因为全局函数其实就是window的属性, 所以在顶层调用全局函数时的this是指window对象.

下面的例子可以很好的说明这一切:

    <SPAN class=kwrd>var</SPAN> o1 = { name: <SPAN class=str>"o1 name"</SPAN> };
    window.name = <SPAN class=str>"window name"</SPAN>;

    <SPAN class=kwrd>function</SPAN> showName()
    {
      alert(<SPAN class=kwrd>this</SPAN>.name);
    }    
    
    o1.show = showName;
    window.show = showName;

    showName();
    o1.show();
    window.show();

 

结果:

image

image

image

结果证明在顶层调用函数和使用window对象调用函数时, this都指向window对象. 而在对象中调用函数时this指向当前对象.

 

七.javascript中的闭包

闭包的概念比较难以理解, 先看闭包的定义:

闭包是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。

简单表达:

闭包就是function实例以及执行function实例时来自环境的变量.

先看下面的例子:

<SPAN class=kwrd><!</SPAN><SPAN class=html>DOCTYPE</SPAN> <SPAN class=attr>html</SPAN> <SPAN class=attr>PUBLIC</SPAN> <SPAN class=kwrd>"-//W3C//DTD XHTML 1.0 Transitional//EN"</SPAN> <SPAN class=kwrd>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>html</SPAN> <SPAN class=attr>xmlns</SPAN><SPAN class=kwrd>="http://www.w3.org/1999/xhtml"</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>head</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>head</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>div</SPAN> <SPAN class=attr>id</SPAN><SPAN class=kwrd>="divResult"</SPAN><SPAN class=kwrd>></</SPAN><SPAN class=html>div</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>script</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/javascript"</SPAN><SPAN class=kwrd>></SPAN>
    <SPAN class=kwrd>function</SPAN> start()
    {
      <SPAN class=kwrd>var</SPAN> count = 0;
      window.setInterval(<SPAN class=kwrd>function</SPAN>()
      {
        document.getElementById(<SPAN class=str>"divResult"</SPAN>).innerHTML += count + <SPAN class=str>"<br/>"</SPAN>;
        count++;
      }, 3000);
    };
    start();
  <SPAN class=kwrd></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>html</SPAN><SPAN class=kwrd>></SPAN>

 

count是start函数体内的变量, 通常我们理解count的作用于是在start()函数内,  在调用start()函数结束后应该也会消失.但是此示例的结果是count变量会一直存在,并且每次被加1:

image

因为count变量是setInterval中创建的匿名函数(就是包含count++的函数)的闭包的一部分!

再通俗的讲, 闭包首先就是函数本身, 比如上面这个匿名函数本身, 同时加上在这个函数运行时需要用到的count变量.

javascript中的闭包是隐式的创建的, 而不像其他支持闭包的语言那样需要显式创建. 我们在C#语言中很少碰到是因为C#中无法在方法中再次声明方法. 而在一个方法中调用另一个方法通常使用参数传递数据.

本文不再详细讲解闭包, 深入学习请参考下面的文章

八.总结

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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)