search
HomeWeb Front-endJS TutorialJavaScript object-oriented and this pointing (with code)

This time I bring you JavaScript object-oriented and this pointing (with code), Using JavaScriptObject-oriented and this pointing What are the precautions, the following is a practical case, Let’s take a look.

Our programming language has gone through a process from "machine-oriented" to "process-oriented" and then to "object-oriented". JavaScript is an object-based language, which is between process-oriented and object-oriented. In the process of learning JavaScript, OOP is a very important part. Let’s discuss the object-oriented approach in JS! ! !

1. Basic issues of OOP

1.1 What are process-oriented and object-oriented?

Process-oriented: Focus on the process steps of how to solve a problem. The characteristic of programming is that each step of the process is implemented by functions one by one, without the concepts of classes and objects.

Object-oriented: Focus on which object solves the problem. The characteristic of programming is that classes appear one after another, and the object is obtained from the class and used to solve specific problems.

For the caller, process orientation requires the caller to implement various functions by himself. Object-oriented, on the other hand, only needs to tell the caller the functions of specific methods in the object, without requiring the caller to understand the implementation details of the method.

1.2 Three major characteristics of object-oriented

Inheritance, encapsulation, polymorphism

1.3 The relationship between classes and objects

① Class: A collection of similar characteristics (properties) and behaviors (methods).

For example: human being-->Attributes: height, weight, gender Method: eating, talking, walking

② Object: From the class, take out an individual with certain attribute values ​​and methods.

For example: Zhang San-->Attributes: Height 180, Weight 180 Method: Talk-->My name is Zhang San, height 180

③ The relationship between classes and objects

Classes are abstract, objects are concrete (classes are the abstraction of objects, objects are the concretization of classes)

explain:

Class is an abstract concept. It can only be said that a class has attributes and methods , but it cannot assign specific values ​​to the attributes. For example, humans have names, but we cannot say what their names are. . .

An object is a specific instance, an individual that assigns specific values ​​to the attributes in the class. For example, if Zhang San is an individual human being, we can say that Zhang San’s name is Zhang San. That is to say, Zhang San has made a specific assignment to each attribute of human beings, so Zhang San is an object generated by humans.

2. Object-oriented in JavaScript

2.1 Steps to create classes and objects

①Create a class (Constructor): The class name must use the big camel case rule, that is, the first letter of each word must be capitalized.

function 类名(属性1){
  this.属性1 = 属性1;
  this.方法 = function(){
   //方法中要调用自身属性,必须要使用this.属性
  }
}

② Instantiate (new) an object through a class.

var obj = new class name (specific value of attribute 1);

obj.property; call property

obj.Method(); Call method

③Notes

>>>The process of new creating an object through the class name is called "instantiation of the class"

>>>This in the class will point to the newly created object when instantiated. Therefore, this.property and this.method actually bind properties and methods to the object that is about to be new.

>>>In a class, to call its own properties, you must use this.property name. If you use the variable name directly, you cannot access the corresponding property.

>>>Class names must use the camel case rule, and pay attention to the difference from ordinary functions.

2.2 Two important attributes constructor and instanceof

①constructor:返回当前对象的构造函数

>>>zhangsan.constructor = Person; √

②instanceof:检测一个对象,是不是一个类的实例;

>>>lisi instanceof Person √ lisi是通过Person类new出的

>>>lisi instanceof Object √ 所有对象都是Object的实例

>>>Person instanceof Object √ 函数本身也是对象

3、 JavaScript中的this指向问题

在上一部分中,我们创建了一个类,并通过这个类new出了一个对象。 但是,这里面出现了大量的this。 很多同学就要懵逼了,this不是“这个”的意思吗?为什么我在函数里面写的this定义的属性,最后到了函数new出的对象呢??

3.1谁最终调用函数,this就指向谁!

① this指向谁,不应该考虑函数在哪声明,而应该考虑函数在哪调用!!

② this指向的,永远只可能是对象,不可能是函数!!

③ this指向的对象,叫做函数的上下文context,也叫函数的调用者。

3.2this指向的规律(与函数的调用方式息息相关!)

① 通过函数名()调用的,this永远指向window

func(); // this--->window
//【解释】 我们直接用一个函数名()调用,函数里面的this,永远指向window。

② 通过对象.方法调用的,this指向这个对象

// 狭义对象
 var obj = {
  name:"obj",
  func1 :func
 };
 obj.func1(); // this--->obj
//【解释】我们将func函数名,当做了obj这个对象的一个方法,然后使用对象名.方法名, 这时候函数里面的this指向这个obj对象。
 // 广义对象
 document.getElementById("p").onclick = function(){
  this.style.backgroundColor = "red";
}; // this--->p
//【解释】对象打点调用还有一个情况,我们使用getElementById取到一个p控件,也是一种广义的对象,用它打点调用函数,则函数中的this指向这个p对象。

③ 函数作为数组的一个元素,用数组下标调用,this指向这个数组

var arr = [func,1,2,3];
arr[0](); // this--->arr
//【解释】这个,我们把函数名,当做数组中的一个元素。使用数组下标调用,则函数中的this将指向这个数组arr。

④ 函数作为window内置函数的回调函数使用,this指向window。比如setTimeout、setInterval等

setTimeout(func,1000);// this--->window
//setInterval(func,1000);
//【解释】使用setTimeout、setInterval等window内置函数调用函数,则函数中的this指向window。

⑤ 函数作为构造函数,使用new关键字调用,this指向新new出的对象

var obj = new func(); //this--->new出的新obj
//【解释】这个就是第二部分我们使用构造函数new对象的语句,将函数用new关键字调用,则函数中的this指向新new出的对象。

3.3关于this问题的面试题

var fullname = 'John Doe';
var obj = {
  fullname: 'Colin Ihrig',
  prop: {
    fullname: 'Aurelio De Rosa',
    getFullname: function() {
      return this.fullname;
    }
  }
};
console.log(obj.prop.getFullname()); 
// 函数的最终调用者 obj.prop 
   
var test = obj.prop.getFullname;
console.log(test()); 
// 函数的最终调用者 test() this-> window
   
obj.func = obj.prop.getFullname;
console.log(obj.func()); 
// 函数最终调用者是obj
   
var arr = [obj.prop.getFullname,1,2];
arr.fullname = "JiangHao";
console.log(arr[0]());
// 函数最终调用者数组

好了,这篇博客,我们了解了什么是面向对象、类和对象的关系、JS中声明类与对象的步骤,以及重点讲解的this指向问题! 希望能够帮助大家真正的理解了this的认知,下面我会继续给大家分享关于面向对象方面的问题。多谢大家的支持!!!

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue中computed属性的使用方法

ajax与跨域jsonp


The above is the detailed content of JavaScript object-oriented and this pointing (with code). For more information, please follow other related articles on the PHP Chinese website!

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
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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 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.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft