Table of Contents
Let’s create an object
Define methods and properties
Constructor version:
Text version:
Now let’s look at the differences:
Use constructor.
To instantiate or not to instantiate
这个和那个
现实世界的用法:表单验证对象
结论
Home CMS Tutorial WordPress Object-oriented basics of JavaScript

Object-oriented basics of JavaScript

Sep 02, 2023 am 11:21 AM
javascript object-oriented basic knowledge

JavaScript has grown in popularity in recent years, in part due to the development of libraries that make it easier to create JavaScript applications/effects for those who don't yet fully master the core language.

Although in the past, people generally believed that JavaScript was a basic language and very "sloppy" with no real foundation; this is no longer the case, especially with large-scale web applications and JSON (JavaScript Object Notation) and other "adaptations" are introduced.

JavaScript can have all the features provided by an object-oriented language, albeit with some extra work that is beyond the scope of this article.

Let’s create an object

    function myObject(){
    
    };
Copy after login

Congratulations, you just created an object. There are two ways to create JavaScript objects: "constructor" and "literal notation". The function above is a constructor, and I'll explain the difference shortly, but until then, this is what an object definition looks like using literal notation.

    var myObject = {
    
    };
Copy after login

Literal is the preferred option for name spacing so that your JavaScript code does not interfere with (and vice versa) other scripts running on the page, and if you are using this object as a single object and do not need multiple instance, whereas the constructor type notation is preferred if you need to perform some initial work before creating the object, or if you need multiple instances of the object (where each instance can change during the lifetime of the script). Let's go ahead and build both objects simultaneously so we can observe the differences.

Define methods and properties

Constructor version:

    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };
Copy after login
Copy after login

Text version:

    var myObject = {
        iAm : 'an object',
        whatAmI : function(){
            alert('I am ' + this.iAm);
        }
    }
Copy after login

For each object, we create a property "iAm" that contains a string value that is used in our object method "whatAmI" which emits the alert message.

Properties are variables created inside an object, and methods are functions created inside an object.

Now is probably a good time to explain how to use properties and methods (although if you're familiar with the library, you may already be doing this).

To use a property, first enter the object it belongs to - so in this case myObject - and then to refer to its internal properties, add a period and then enter the property name so it ends up looking like myObject. iAm (this will return "an object").

It's the same for methods except that the execution method, like any function, must be followed by parentheses; otherwise you will just return a reference to the function, not what the function actually returns content. So it would look like myObject.whatAmI() (which would remind "I am an object").

Now let’s look at the differences:

  • The properties and methods of a constructor object are defined using the keyword "this" in front of it, while the literal version is not.
  • In constructor objects, the "values" of properties/methods are defined after the equal sign "=", while in the literal version they are defined after the colon ":".
  • Constructors can have an (optional) semicolon ";" at the end of each property/method declaration, whereas in the literal version if you have multiple properties or methods they must be separated by a comma "," , and they cannot be followed by a semicolon, otherwise JavaScript will return an error.

There are also differences in how these two types of object declarations are used.

To use a literally annotated object, you simply use it by referencing its variable name, so whenever you need it, you can call it by typing;

    myObject.whatAmI();
Copy after login

Using a constructor, you need to instantiate (create a new instance of the object) first; you can do this by typing;

    var myNewObject = new myObject();
    myNewObject.whatAmI();
Copy after login

Use constructor.

Let's take the previous constructor and build on it to perform some basic (but dynamic) operations when instantiating it.

    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };
Copy after login
Copy after login

Just like any JavaScript function, we can use parameters in the constructor;

function myObject(what){
	this.iAm = what;
	this.whatAmI = function(language){
		alert('I am ' + this.iAm + ' of the ' + language + ' language');
	};
};
Copy after login

Now let's instantiate our object and call its WhatAmI method while filling in the required fields.

    var myNewObject = new myObject('an object');
    myNewObject.whatAmI('JavaScript');
Copy after login

This will warn "I am an object of the JavaScript language."

To instantiate or not to instantiate

I mentioned before the difference between object constructors and object literals, when changes are made to an object literal it affects that object throughout the script, whereas when a constructor is instantiated and then changed it instance, it does not affect any other instances of that object. Let's try an example;

First we will create an object literal;

	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'
    
    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a new property', as expected
Copy after login

Even if you create a new variable and point it to the object, it will have the same effect.

	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'
    
    //define new variable with object as value
    var sameObject = myObjectLiteral;
    
    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';
    
    //alert current myProperty
    alert(sameObject.myProperty); //this will still alert 'this is a new property'
Copy after login

Now let's try a similar exercise using constructors.

	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }
    
    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();
    
    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();
    
    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a property'
     
     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will alert 'this is a property'
Copy after login

As expected, both return the correct value, but let's change the myProperty of one of the instances.

	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }
    
    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();
    
    //change myProperty of the first instance
    constructorOne.myProperty = 'this is a new property';
    
    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();
    
    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a new property'
     
     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will still alert 'this is a property'
Copy after login

从这个示例中可以看出,即使我们更改了 constructorOne 的属性,它也没有影响 myObjectConstructor,因此也没有影响 constructorTwo。即使在更改 constructorOne 的 myProperty 属性之前实例化了 constructorTwo,它仍然不会影响 constructorTwo 的 myProperty 属性,因为它是 JavaScript 内存中完全不同的对象实例。

那么您应该使用哪一个呢?好吧,这取决于情况,如果您的脚本只需要一个此类对象(正如您将在本文末尾的示例中看到的那样),则使用对象文字,但如果您需要一个对象的多个实例,其中每个实例彼此独立,并且根据其构造方式可以具有不同的属性或方法,然后使用构造函数。

这个和那个

在解释构造函数时,出现了很多“this”关键字,我想这是讨论作用域的更好时机!

现在您可能会问“您所说的范围是什么”? JavaScript 中的作用域是基于函数/对象的,因此这意味着如果您在函数之外,则无法使用在函数内部定义的变量(除非您使用闭包)。

然而,存在作用域链,这意味着另一个函数内的函数可以访问其父函数中定义的变量。让我们看一些示例代码。

<script type="text/javascript">

var var1 = 'this is global and is available to everyone';

function function1(){

	var var2 = 'this is only available inside function1 and function2';	
	
	function function2(){
	
		var var3 = 'this is only available inside function2';
	
	}		
	
}

</script>
Copy after login

正如你在这个例子中看到的, var1 是在全局对象中定义的,可用于所有函数和对象, var2 是在 function1 中定义的,可用于 function1 和 function2,但是如果你尝试引用从全局对象中获取它会给出错误“var2 未定义”,var3 只能由 function2 访问。

那么“this”指的是什么呢?在浏览器中,“this”引用窗口对象,因此从技术上讲,窗口是我们的全局对象。如果我们在一个对象内部,“this”将引用该对象本身,但是如果您在一个函数内部,这仍然会引用窗口对象,同样,如果您在一个对象内的方法内部,“ this' 将引用该对象。

由于我们的作用域链,如果我们位于子对象(对象内的对象)内部,“this”将引用子对象而不是父对象。

作为旁注,还值得补充的是,当使用 setInterval、setTimeout 和 eval 等函数时,当您通过其中之一执行函数或方法时,“this”指的是 window 对象,因为这些是 window 的方法,所以 setInterval() 和 window.setInterval() 是相同的。

好吧,现在我们已经解决了这个问题,让我们做一个真实的示例并创建一个表单验证对象!

现实世界的用法:表单验证对象

首先我必须向您介绍我们将创建的 addEvent 函数,它是 ECMAScript 的(Firefox、Safari 等)addEventListener() 函数和 Microsoft ActiveX Script 的 AttachEvent() 函数的组合。

    function addEvent(to, type, fn){
        if(document.addEventListener){
            to.addEventListener(type, fn, false);
        } else if(document.attachEvent){
            to.attachEvent('on'+type, fn);
        } else {
            to['on'+type] = fn;
        }	
    };
Copy after login

这将创建一个具有三个参数的新函数,to 是我们将事件附加到的 DOM 对象,type 是事件类型,fn 是触发事件时运行的函数。它首先检查是否支持 addEventListener,如果支持,它将使用它,如果不支持,它将检查 AttachEvent,如果其他所有方法都失败,您可能正在使用 IE5 或同样过时的东西,因此我们将事件直接添加到其事件属性上(注意:第三个选项将覆盖可能已附加到事件属性的任何现有函数,而前两个选项会将其作为附加函数添加到其事件属性中)。

现在让我们设置我们的文档,使其与您开发 jQuery 内容时可能看到的类似。

在 jQuery 中你会有;

    $(document).ready(function(){
        //all our code that runs after the page is ready goes here
    });
Copy after login

使用我们的 addEvent 函数;

    addEvent(window, 'load', function(){
		//all our code that runs after the page is ready goes here
	});
Copy after login

现在我们的 Form 对象。

var Form = {

	validClass : 'valid',
	
	fname : {
		minLength : 1,		
		maxLength : 15,	
		fieldName : 'First Name'
	},
    
	lname : {
		minLength : 1,		
		maxLength : 25,
		fieldName : 'Last Name'
	},
	
    
	validateLength : function(formEl, type){
		if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){	
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		} else {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)
			formEl.className += ' '+Form.validClass;
			return true;
		}
	},
	
    
	validateEmail : function(formEl){
		var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
		var emailTest = regEx.test(formEl.value);		 
		if (emailTest) {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)			
			formEl.className += ' '+Form.validClass;            
			return true;
		} else {
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		}			
	},		
	
	getSubmit : function(formID){    
		var inputs = document.getElementById(formID).getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++){
			if(inputs[i].type == 'submit'){
				return inputs[i];
			}		
		}		
		return false;
	}			
		
};
Copy after login

所以这是非常基本的,但可以很容易地扩展。

为了解决这个问题,我们首先创建一个新属性,它只是“有效”CSS 类的字符串名称,当应用于表单字段时,会添加有效的效果,例如绿色边框。我们还定义了两个子对象,fnamelname,因此我们可以定义它们自己的属性,这些属性可以被其他地方的方法使用,这些属性是minLength,这是这些字段可以拥有的最小字符数, maxLength 是字段可以拥有的最大字符数,而 fieldName 实际上并没有被使用,但可以用于诸如在错误消息中使用用户友好的字符串识别字段之类的事情(例如“名字字段”)是必需的。')。

接下来我们创建一个 validateLength 方法,它接受两个参数: formEl 要验证的 DOM 元素和 type ,它引用要使用的子对象之一(即 fname 或 lname)。该函数检查字段的长度是否在 minLength 和 maxLength 范围之间,如果不是,那么我们从元素中删除有效类(如果存在)并返回 false,否则如果是,那么我们添加有效类并返回正确。

然后我们有一个 validateEmail 方法,它接受 DOM 元素作为参数,然后我们根据电子邮件类型正则表达式测试这个 DOM 元素值;如果通过,我们再次添加我们的类并返回 true,反之亦然。

最后我们有一个 getSubmit 方法。该方法获得表单的 id,然后循环遍历指定表单内的所有输入元素,以查找哪一个具有提交类型 (type="submit")。此方法的原因是返回提交按钮,以便我们可以禁用它,直到表单准备好提交。

让我们让这个验证器对象在真实的表单上工作。首先我们需要 HTML。

    <body>
    
    <form id="ourForm">
        <label>First Name</label><input type="text" /><br />
        <label>Last Name</label><input type="text" /><br />
        <label>Email</label><input type="text" /><br />
        <input type="submit" value="submit" />
    </form>
    
    </body>
Copy after login

现在让我们使用 JavaScript 访问这些输入对象,并在表单提交时验证它们。

addEvent(window, 'load', function(){
	
	
	var ourForm = document.getElementById('ourForm');	
	var submit_button = Form.getSubmit('ourForm');
	submit_button.disabled = 'disabled';
	
	function checkForm(){
		var inputs = ourForm.getElementsByTagName('input');
		if(Form.validateLength(inputs[0], Form.fname)){
			if(Form.validateLength(inputs[1], Form.lname)){
				if(Form.validateEmail(inputs[2])){ 					 
                     
						submit_button.disabled = false;
						return true;
										
				}
			}
		}
			
		submit_button.disabled = 'disabled';
		return false;
		
	};
	
	checkForm();		
	addEvent(ourForm, 'keyup', checkForm);
	addEvent(ourForm, 'submit', checkForm);
      
	
});
Copy after login

让我们分解一下这段代码。

我们将代码包装在 addEvent 函数中,以便在加载窗口时运行此脚本。首先,我们使用表单 ID 获取表单并将其放入名为 ourForm 的变量中,然后获取提交按钮(使用表单对象 getSubmit 方法)并将其放入名为 submit_button 的变量中,然后设置提交按钮禁用属性为“禁用”。

接下来我们定义一个 checkForm 函数。这会将表单字段内的所有输入存储为一个数组,并将其附加到一个名为..你猜对了的变量.. inputs!然后它定义了一些嵌套的 if 语句,这些语句根据我们的 Form 方法测试输入数组内的每个字段。这就是我们在方法中返回 true 或 false 的原因,因此如果它返回 true,我们将传递该 if 语句并继续执行下一个,但如果它返回 false,我们将退出 if 语句。

根据我们的函数定义,我们在页面最初加载时执行 checkForm 函数,并将该函数附加到 keyup 事件和提交事件。

您可能会问,如果我们禁用了提交按钮,为什么还要附加提交。好吧,如果您专注于输入字段并按下 Enter 键,它将尝试提交表单,我们需要对此进行测试,因此我们的 checkForm 函数返回 true(提交表单)或 false(不提交)形式)。

结论

因此,我们学习了如何在 JavaScript 中定义不同的对象类型并在其中创建属性和方法。我们还学习了一个漂亮的 addEvent 函数,并在基本的现实示例中使用我们的对象。

这就是 JavaScript 面向对象的基础知识。希望这可以让您开始构建自己的 JavaScript 库!如果您喜欢这篇文章并对其他 JavaScript 相关主题感兴趣,请将它们发布在评论中,我很乐意继续撰写它们。感谢您的阅读。

为什么不看看 CodeCanyon 上的 JavaScript 项目范围。您可以找到用于创建滑块、倒计时、加载器和上传器等的脚本。

Object-oriented basics of JavaScript

The above is the detailed content of Object-oriented basics of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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)

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming Jun 05, 2024 pm 08:50 PM

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

How to implement an online electronic signature system using WebSocket and JavaScript How to implement an online electronic signature system using WebSocket and JavaScript Dec 18, 2023 pm 03:09 PM

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online

See all articles