google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Bước đầu làm quen với JavaScript hướng đối tượng Trong một vài năm gần đây, ngôn ngữ lập trình web JavaScript phát triển khá mạnh, với sự hỗ trợ của rất nhiều nền tảng như các hệ điều hành di động, các máy tính bảng, các điện thoại thông minh. Từ sự hỗ trợ mạnh mẽ này mà bản thân ngôn ngữ JavaScript cũng có những cải tiến vượt bậc. Và hiện tại ngôn ngữ này đã hỗ trợ lập trình hướng đối tượng khá tốt. Hãy vào trang chi tiết để xem cách tiếp cận cách lập trình hướng đối tượng trong JavaScript nếu bạn chưa quen.


Tạo video bằng AI chỉ với giọng nói hoặc văn bản



Ứng dụng video AI MIỄN PHÍ hàng đầu của bạn! Tự động hóa video AI đầu tiên của bạn. Tạo Video Chuyên Nghiệp Của Bạn Trong 5 Phút Bằng AI Không Cần Thiết Bị Hoặc Kỹ Năng Chỉnh Sửa Video. Sản xuất video dễ dàng dành cho nhà tiếp thị nội dung.
Ứng dụng video AI KHÔNG GIỚI HẠN miễn phí trong tay bạn

This and That

While explaining constructor functions, there were a lot of 'this' keywords being thrown around and I figure what better time to talk about scope!

Now you might be asking 'what is this scope you speak of'?' Scope in JavaScript is function/object based, so that means if you're outside of a function, you can't use a variable that is defined inside a function (unless you use a closure).

There is however a scope chain, which means that a function inside another function can access a variable defined in its parent function. Let's take a look at some example code.

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

As you can see in this example, var1 is defined in the global object and is available to all functions and object, var2 is defined inside function1 and is available to function1 and function2, but if you try to reference it from the global object it will give you the error 'var2 is undefined', var3 is only accessible to function2.

So what does 'this' reference? Well in a browser, 'this' references the window object, so technically the window is our global object. If we're inside an object, 'this' will refer to the object itself however if you're inside a function, this will still refer to the window object and likewise if you're inside a method that is within an object, 'this' will refer to the object.

Due to our scope chain, if we're inside a sub-object (an object inside an object), 'this' will refer to the sub-object and not the parent object.

As a side note, it's also worth adding that when using functions like setInterval, setTimeout and eval, when you execute a function or method via one of these, 'this' refers to the window object as these are methods of window, so setInterval() and window.setInterval() are the same.

Ok now that we have that out of the way, let's do a real world example and create a form validation object!

Real world Usage: A Form Validation Object

First I must introduce you to the addEvent function which we will create and is a combination of ECMAScript's (Firefox, Safari, etc.. ) addEventListener() function and Microsoft ActiveX Script's attachEvent() function.

    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;
        }	
    };

This creates a new function with three arguments, to being the DOM object we are attaching the event to, type being the type of event and fn being the function run when the event is triggered. It first checks whether addEventListener is supported, if so it will use that, if not it will check for attachEvent and if all else fails you are probably using IE5 or something equally obsolete so we will add the event directly onto its event property (note: the third option will overwrite any existing function that may have been attached to the event property while the first two will add it as an additional function to its event property).

Now let's set up our document so it is similar to what you might see when you develop jQuery stuff.

In jQuery you would have;

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

Using our addEvent function we have;

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

Now for our Form object.

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;
	}			
		
};

So this is quite basic but can easily be expanded upon.

To break this down first we create a new property which is just the string name of our 'valid' css class that when applied to the form field, adds valid effects such as a green border. We also define our two sub-objects, fname and lname, so we can define their own properties that can be used by methods elsewhere, these properties are minLength which is the minimum amount of characters these fields can have, maxLength which is the max characters the field can have and fieldName which doesn't actually get used, but could be grabbed for things like identifying the field with a user friendly string in an error message (eg. 'First Name field is required.').

Next we create a validateLength method that accepts two arguments: formEl the DOM element to validate and the type which refers to one of the sub-object to use (i.e. fname or lname). This function checks whether the length of the field is between the minLength and maxLength range, if it's not then we remove our valid class (if it exists) from the element and return false, otherwise if it is then we add the valid class and return true.

Then we have a validateEmail method which accepts a DOM element as an arguement, we then test this DOM elements value against an email type regular expression; again if it passes we add our class and return true and vice versa.

Finally we have a getSubmit method. This method is given the id of the form and then loops through all input elements inside the specified form to find which one has a type of submit (type="submit"). The reason for this method is to return the submit button so we can disable it until the form is ready to submit.

Let's put this validator object to work on a real form. First we need our 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>

Now let's access these input objects using JavaScript and validate them when the form submits.

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);
      
	
});

Let's break down this code.

We wrap our code in the addEvent function so when the window is loaded this script runs. Firstly we grab our form using its ID and put it in a variable named ourForm, then we grab our submit button (using our Form objects getSubmit method) and put it in a variable named submit_button, and then set the submit buttons disabled attribute to 'disabled'.

Next we define a checkForm function. This stores all the inputs inside the form field as an array and we attach it to a variable named.. you guessed it.. inputs! Then it defines some nested if statements which test each of the fields inside the inputs array against our Form methods. This is the reason we returned true or false in our methods, so if it returns true, we pass that if statement and continue onto the next, but if it returns false, we exit the if statements.

Following our function definition, we execute the checkForm function when the page initially loads and also attach the function to a keyup event and a submit event.

You might be asking, why attach to submit if we disabled the submit button. Well if you are focused on an input field and hit the enter key, it will attempt to submit the form and we need to test for this, hence the reason our checkForm function returns true (submits the form) or false (doesn't submit form).

Conclusion

So we learned how to define the different object types within JavaScript and create properties and methods within them. We also learned a nifty addEvent function and got to use our object in a basic real world example.

This concludes the basics of JavaScript Object Orientation. Hopefully, this may start you on your way to building your own JavaScript library! If you liked this article and are interested in other JavaScript related topics, post them in the comments as I'd be happy to continue writing them. Thanks for reading.

Ứng dụng AI Video.com
Tạo video doanh nghiệp của bạn bằng AI chỉ với giọng nói hoặc văn bản

chatGPTaz.com
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn

Ứng dụng AI Video
Ứng dụng video AI MIỄN PHÍ đầu tiên của bạn

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ

Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ

Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu tặng $500 cho người dùng mới
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Tín dụng quảng cáo TikTok miễn phí
Làm chủ quảng cáo TikTok cho hoạt động tiếp thị doanh nghiệp của bạn

Dall-E-OpenAI.com
Tự động tạo ra hình ảnh sáng tạo với AI

chatGPT4.win
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn

Sản phẩm AI đầu tiên của Elon Musk - Grok/UN.com
Nói chuyện với Grok AI Chatbot bằng ngôn ngữ của bạn

Công cụ.win
Mở trung tâm công cụ miễn phí để mọi người sử dụng với hàng trăm công cụ

GateIO.gomymobi.com
Airdrop miễn phí để nhận, chia sẻ lên đến 150.000 đô la cho mỗi dự án

iPhoneKer.com
Tiết kiệm tới 630$ khi mua iPhone 16 mới

Mua Robot Tesla Optimus
Đặt mua Tesla Bot: Robot Optimus Gen 2 ngay hôm nay với giá dưới 20.000 đô la

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web