Object-oriented basics of JavaScript
Sep 02, 2023 am 11:21 AMJavaScript 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(){ };
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 = { };
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); }; };
Text version:
var myObject = { iAm : 'an object', whatAmI : function(){ alert('I am ' + this.iAm); } }
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();
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();
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); }; };
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'); }; };
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');
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
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'
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'
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'
從這個示例中可以看出,即使我們更改了 constructorOne 的屬性,它也沒有影響 myObjectConstructor,因此也沒有影響 constructorTwo。即使在更改 constructorOne 的 myProperty 屬性之前實例化了 constructorTwo,它仍然不會影響 constructorTwo 的 myProperty 屬性,因為它是 JavaScript 內(nèi)存中完全不同的對象實例。
那么您應(yīng)該使用哪一個呢?好吧,這取決于情況,如果您的腳本只需要一個此類對象(正如您將在本文末尾的示例中看到的那樣),則使用對象文字,但如果您需要一個對象的多個實例,其中每個實例彼此獨(dú)立,并且根據(jù)其構(gòu)造方式可以具有不同的屬性或方法,然后使用構(gòu)造函數(shù)。
這個和那個
在解釋構(gòu)造函數(shù)時,出現(xiàn)了很多“this”關(guān)鍵字,我想這是討論作用域的更好時機(jī)!
現(xiàn)在您可能會問“您所說的范圍是什么”? JavaScript 中的作用域是基于函數(shù)/對象的,因此這意味著如果您在函數(shù)之外,則無法使用在函數(shù)內(nèi)部定義的變量(除非您使用閉包)。
然而,存在作用域鏈,這意味著另一個函數(shù)內(nèi)的函數(shù)可以訪問其父函數(shù)中定義的變量。讓我們看一些示例代碼。
<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>
正如你在這個例子中看到的, var1
是在全局對象中定義的,可用于所有函數(shù)和對象, var2
是在 function1 中定義的,可用于 function1 和 function2,但是如果你嘗試引用從全局對象中獲取它會給出錯誤“var2 未定義”,var3
只能由 function2 訪問。
那么“this”指的是什么呢?在瀏覽器中,“this”引用窗口對象,因此從技術(shù)上講,窗口是我們的全局對象。如果我們在一個對象內(nèi)部,“this”將引用該對象本身,但是如果您在一個函數(shù)內(nèi)部,這仍然會引用窗口對象,同樣,如果您在一個對象內(nèi)的方法內(nèi)部,“ this' 將引用該對象。
由于我們的作用域鏈,如果我們位于子對象(對象內(nèi)的對象)內(nèi)部,“this”將引用子對象而不是父對象。
作為旁注,還值得補(bǔ)充的是,當(dāng)使用 setInterval、setTimeout 和 eval 等函數(shù)時,當(dāng)您通過其中之一執(zhí)行函數(shù)或方法時,“this”指的是 window 對象,因為這些是 window 的方法,所以 setInterval() 和 window.setInterval() 是相同的。
好吧,現(xiàn)在我們已經(jīng)解決了這個問題,讓我們做一個真實的示例并創(chuàng)建一個表單驗證對象!
現(xiàn)實世界的用法:表單驗證對象
首先我必須向您介紹我們將創(chuàng)建的 addEvent 函數(shù),它是 ECMAScript 的(Firefox、Safari 等)addEventListener() 函數(shù)和 Microsoft ActiveX Script 的 AttachEvent() 函數(shù)的組合。
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; } };
這將創(chuàng)建一個具有三個參數(shù)的新函數(shù),to
是我們將事件附加到的 DOM 對象,type
是事件類型,fn
是觸發(fā)事件時運(yùn)行的函數(shù)。它首先檢查是否支持 addEventListener,如果支持,它將使用它,如果不支持,它將檢查 AttachEvent,如果其他所有方法都失敗,您可能正在使用 IE5 或同樣過時的東西,因此我們將事件直接添加到其事件屬性上(注意:第三個選項將覆蓋可能已附加到事件屬性的任何現(xiàn)有函數(shù),而前兩個選項會將其作為附加函數(shù)添加到其事件屬性中)。
現(xiàn)在讓我們設(shè)置我們的文檔,使其與您開發(fā) jQuery 內(nèi)容時可能看到的類似。
在 jQuery 中你會有;
$(document).ready(function(){ //all our code that runs after the page is ready goes here });
使用我們的 addEvent 函數(shù);
addEvent(window, 'load', function(){ //all our code that runs after the page is ready goes here });
現(xiàn)在我們的 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; } };
所以這是非?;镜?,但可以很容易地擴(kuò)展。
為了解決這個問題,我們首先創(chuàng)建一個新屬性,它只是“有效”CSS 類的字符串名稱,當(dāng)應(yīng)用于表單字段時,會添加有效的效果,例如綠色邊框。我們還定義了兩個子對象,fname
和lname
,因此我們可以定義它們自己的屬性,這些屬性可以被其他地方的方法使用,這些屬性是minLength
,這是這些字段可以擁有的最小字符數(shù), maxLength
是字段可以擁有的最大字符數(shù),而 fieldName
實際上并沒有被使用,但可以用于諸如在錯誤消息中使用用戶友好的字符串識別字段之類的事情(例如“名字字段”)是必需的。')。
接下來我們創(chuàng)建一個 validateLength 方法,它接受兩個參數(shù): formEl
要驗證的 DOM 元素和 type
,它引用要使用的子對象之一(即 fname 或 lname)。該函數(shù)檢查字段的長度是否在 minLength 和 maxLength 范圍之間,如果不是,那么我們從元素中刪除有效類(如果存在)并返回 false,否則如果是,那么我們添加有效類并返回正確。
然后我們有一個 validateEmail 方法,它接受 DOM 元素作為參數(shù),然后我們根據(jù)電子郵件類型正則表達(dá)式測試這個 DOM 元素值;如果通過,我們再次添加我們的類并返回 true,反之亦然。
最后我們有一個 getSubmit 方法。該方法獲得表單的 id,然后循環(huán)遍歷指定表單內(nèi)的所有輸入元素,以查找哪一個具有提交類型 (type="submit")。此方法的原因是返回提交按鈕,以便我們可以禁用它,直到表單準(zhǔn)備好提交。
讓我們讓這個驗證器對象在真實的表單上工作。首先我們需要 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>
現(xiàn)在讓我們使用 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); });
讓我們分解一下這段代碼。
我們將代碼包裝在 addEvent 函數(shù)中,以便在加載窗口時運(yùn)行此腳本。首先,我們使用表單 ID 獲取表單并將其放入名為 ourForm
的變量中,然后獲取提交按鈕(使用表單對象 getSubmit 方法)并將其放入名為 submit_button
的變量中,然后設(shè)置提交按鈕禁用屬性為“禁用”。
接下來我們定義一個 checkForm 函數(shù)。這會將表單字段內(nèi)的所有輸入存儲為一個數(shù)組,并將其附加到一個名為..你猜對了的變量.. inputs
!然后它定義了一些嵌套的 if 語句,這些語句根據(jù)我們的 Form 方法測試輸入數(shù)組內(nèi)的每個字段。這就是我們在方法中返回 true 或 false 的原因,因此如果它返回 true,我們將傳遞該 if 語句并繼續(xù)執(zhí)行下一個,但如果它返回 false,我們將退出 if 語句。
根據(jù)我們的函數(shù)定義,我們在頁面最初加載時執(zhí)行 checkForm 函數(shù),并將該函數(shù)附加到 keyup 事件和提交事件。
您可能會問,如果我們禁用了提交按鈕,為什么還要附加提交。好吧,如果您專注于輸入字段并按下 Enter 鍵,它將嘗試提交表單,我們需要對此進(jìn)行測試,因此我們的 checkForm 函數(shù)返回 true(提交表單)或 false(不提交)形式)。
結(jié)論
因此,我們學(xué)習(xí)了如何在 JavaScript 中定義不同的對象類型并在其中創(chuàng)建屬性和方法。我們還學(xué)習(xí)了一個漂亮的 addEvent 函數(shù),并在基本的現(xiàn)實示例中使用我們的對象。
這就是 JavaScript 面向?qū)ο蟮幕A(chǔ)知識。希望這可以讓您開始構(gòu)建自己的 JavaScript 庫!如果您喜歡這篇文章并對其他 JavaScript 相關(guān)主題感興趣,請將它們發(fā)布在評論中,我很樂意繼續(xù)撰寫它們。感謝您的閱讀。
為什么不看看 CodeCanyon 上的 JavaScript 項目范圍。您可以找到用于創(chuàng)建滑塊、倒計時、加載器和上傳器等的腳本。
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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.

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.

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.

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

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.

What basic knowledge do you need to learn canvas? With the development of modern web technology, using the <canvas> tag in HTML5 for drawing has become a common way. Canvas is an HTML element used to draw graphics, animations and other images, which can be manipulated and controlled using JavaScript. If you want to learn canvas and master its basic knowledge, the following will introduce it to you in detail. HTML and CSS basics: before learning canvas
