search
HomeWeb Front-endJS Tutorial解析JavaScript面向对象概念中的Object类型与作用域_基础知识

引用类型

引用类型主要包括:Object 类型、Array 类型、Date 类型、RegExp 类型、Function 类型等等。

引用类型使用时,需要从它们身上生成一个对象(实例)。也就是说,引用类型相当于一个模版,当我们想要用某个引用类型的时候,就需要用这个模版来生成一个对象来使用,所以引用类型有时候也称作对象定义。

例如,我们需要生成一个 person 对象,来定义某人的个人信息和行为,那么我们就需要依赖 Object 类型:

var person = new Object();
person.name = "jiangshui";
person.sayName = function(){
  console.log(this.name);
}

上面的这个 person 对象,通过 new 操作符使用 Object 类型这个“模版”定义。之后就可以对这个对象添加属性 name 和方法 sayName 了。属性和方法是 Object 类型具有的“功能”,所以通过 Object 等引用类型创建的对象就可以用这个了。

创建对象不一定非得需要用 new 操作符,有一些类型可以简化的创建,例如创建一个上面那样的 Object 类型的对象,也可以使用下面两种方法:

var person = {};
person.name = "jiangshui";
person.sayName = function(){
  console.log(this.name);
}

var person = {
  name : "jiangshui",
  sayName : function(){
    console.log(this.name);
  }
};

{}操作符的功能就跟 new Object() 一样,简化了操作。上面两种写法也有一些区别,第一种是“追加”,也就是在之前的定义中,继续添加属性或者方法,如果之前已经存在了同名属性方法,则会覆盖。而第二种是“取代”,就是不管前面是否定义 person 对象的属性和方法,这个方法会用新定义的内容,整个替换掉之前定义的。因为引用类型生成的对象,是储存在内存中的一块区域,然后将其指针保存在某变量中(person),第二种写法,是生成了一个新对象(新内存区域),然后将 person 变量指向了新内存区域,所以就把之前的取代了。了解这一点对后面理解,至关重要。

其他引用类型的用法大致一致,例如 Array 类型,也可以用 [] 来生成对象,或者直接定义。生成数组对象之后,就可以按照数组的格式存储信息内容,此外对象会得到 Array 类型中定义的那些方法,例如 push、shift、sort 等等,就可以调用这些方法,例如:

var colors = [];
colors.push('red','green');
console.log(colors);

上面代码就是通过 Array 类型创建一个数组类型的对象,然后调用 Array 类型里面之前定义的 push 方法,向对象里面添加了 red 和 green 两个值,最后在控制台打印出来,就可以看到了。

call 和 apply 方法

这两个方法是 Function 类型提供的,也就是说,可以在函数上面使用。call 和 apply 方法的功能一样,就是可以扩充函数运行的作用域,区别就在于使用 call 的时候,传递给函数的参数必须逐个列举出来,而 apply 方法却不用。这样可以根据自己函数的要求来决定使用 call 或者 apply。

扩充函数运行的作用域是什么意思?举个例子你就明白了。

你可以这样理解,函数被包裹在一个容器(作用域)里面,在这个容器里面存在一些变量或者其他东西,当函数运行,调用这些变量等,就会在当前容器里面找这个东西。这个容器其实外面还包裹了一个更大的容器,如果当前小容器没有的话,函数会到更大的容器里面寻找,依次类推,一直找到最大的容器 window 对象。但是如果函数在当前小容器里面运行的时候,小容器里面有对应变量等,即便是大容器里面也有,函数还是会调用自己容器里面的。

而 call 和 apply 方法,就是解决这个问题,突破容器的限制。就前面例子:

var person = {
  name : "jiangshui",
  sayName : function(){
    console.log(this.name);
  }
};

打开 Chrome 的 Console 之后,粘贴进去执行一下,之后再执行 person.sayName() 可以看到

2016510174813378.png (926×572)

这时候,person 就是一个容器,其中创建了一个 sayName 方法(函数),执行的时候,必须在 person 作用域下面执行。当在最下面直接执行的时候,也就是在 window 的作用域下面执行会报错 not defined,因为 window 下面没有定义 sayName 方法。而里面的 this 指针,是一个比较特殊的东西,它指向当前作用域,this.name 的意思,就是调用当前作用域下面的 name 值。

下面我们为 window 对象添加一个 name 属性:

window.name = "yujiangshui";

或者直接

name = "yujiangshui";

因为 window 是最大的容器,所以 window 可以省略掉,所有定义的属性或者变量,都挂靠到 window 上面去了,不信可以看:

2016510174850232.png (486×412)

那现在我们就想在 window 这个大容器下面,运行 person 小容器里面的 sayName 方法,就需要用 call 或 apply 来扩充 sayName 方法的作用域。执行下面语句:

person.sayName.call(window);

或者

person.sayName.call(this);

输出的结果都是一样的,你也可以换用 apply 看看效果,因为这个 demo 太简单的,不需要传递参数,所以 call 和 apply 功能效果就完全一致了。

2016510174922644.png (438×360)

解释一下上面代码,sayName 首先是 Function 类型的实例,也就具有了 call 方法和 apply 方法,call 和 apply 方法既然是 Function 类型的方法,所以就需要用这种方式调用 person.sayName.call(window) 而不是什么 person.sayName().call(window) 之类的。

然后 call 和 apply 方法的参数,就是一个作用域(对象),表示将前面的函数在传递进去的作用域下面运行。将 window 这对象传递进去之后,sayName 方法中的 this.name 指向的就是 window.name,于是就扩充了作用域。

为什么传递 window 和 this 都是一样的效果?因为我们当前执行这个函数的位置是 window,前面说过 this 指针指向的是当前作用域,所以 this 指向的就是 window,所以就等于 window。

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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

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尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor