Lập trình JavaScript hướng đối tượng dành cho người mới Bài viết này cung cấp vài khái niệm cơ bản về lập trình hướng đối tượng trong ngôn ngữ JavaScript dành cho người mới làm quen với lập trình.

Nhãn: lập trình JavaScript, JavaScript hướng đối tượng, người mới, ngôn ngữ JavaScript

Miễn phí web hosting 1 năm đầu tại iPage

Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệ nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

This post will cover the following topics:

  • Javascript is not a toy!
  • How to define a class
  • How to set Publich methods
  • How to set Private variables
  • How to set static methods

JavaScript for Dummies?

Programming languages are like football teams - it doesn't matter which you like, you will support it and protect its interest no matter what. Back in the days when i was young, I remember the same old discussion between two development teams where i used to work - C++ vs. Delphi. I guess its an endless discussion where the people and the languages change but the content basically stay the same.
What's weird is that when i talk to fellow developers about JavaScript i get a weird feeling that everybody looks at it as more of a toy rather than a powerful client side development tool. The major critic that i get is this is a very simple functional language, that cannot match to the object oriented concept that drive most languages. One friend even told me that this is a language for bored teenagers.
I agree - JavaScript is an easy to learn language, but that doesn't mean that it's a simple one. I see it as a positive thing that you can quickly achieve your goals without needing to know all the language capabilities, and you can learn very fast how to really use the language capabilities to accomplish things even better or faster.
I decided to show how you can shape JavaScript to be used as an Object Oriented language. I don't think that you must code JavaScript always in object oriented style, but you should have this ability and choose when you think it's the best solution to implement.

In this post i will focus on the basics of Object Oriented programming - public, private and static declarations.

Defining a Class

In Javascript everything is an object, even functions. In order to define a new class we should just define a new function like so:

1.function Player(url){}

No in order to create an instance of this class we can write the following:

1.var player1 = new Player("");

This line of code will create a new instance of the function object and return the reference to it. Not to confuse, but if the function return a value it won't be placed in player1. for example, let's say you have a function like so:

1.function f1(){ return 100;}
2.var a = f1();
3.var b = new f1();

The difference between the two is that a will be assigned with 100 while b will be assigned with the reference to a new f1 function object.

Public Methods

As in any object oriented language, the first thing you would like to do is define some public methods for your class. In Javascritp we will use the prototype keyword to setup new methods for this class. You can do this like so:

01.function Player(url){
04.Player.prototype.start = function(){
05.// some stuff here...
07.Player.prototype.stop = function(){
08.// some stufff here...

For those of you who prefer to create classes encapsulated in one declaration you can also write the same code as so:

01.function Player(url){
04.Player.prototype = {
05.    start: function(){
06.        // some stuff here...
07.    } ,
08.    stop: function(){
09.        // some stuff here...
10.    }

These two declarations achieve the same result. This is part of the reasons that i love javascript so much - it can be so simple and so complicated at the same time.
Now you can use the class methods as so:

1.var player1 = new Player("");

Public Variables

In order to set public variables we will use the this keyword that allow us to preserve state for our object.

1.function Player(url){
2.    this.url = url;

Now we have a public variable that can be accessed using the class properties as so:

1.var player1 = new Player("");

Usually it is bad practice to allow access to the class inner variables, and such variables needs to be set private.

Private Variables

In order to create private variables we would simple declare them in the constructor as so:

1.function Player(url){
2.    var m_url = url;

Now the variable m_url is not accessible to anyone. Well that doesn't make sense, right? We want to allow our public methods to access the data.
We solve this using closure. A closure is a protected variable space, created by using nested functions. In order to better understand it we first need to understand how JavaScript function declaration works. Function declaration in Javascritp is based on two main concepts: lexically scoped and function-level scope. Lexically means that function run in the scope they are defined in and not in the scope they are executed in, as other language usually do. Function-level means, like most languages, that a variable declared in function is not accessible outside that function. Using these concepts we can now declare our private variables that will be accessible to our public methods:

01.function Player(url){
02.    var m_url = url;
03.    this.start = function(){
04.        //now i can access m_url
05.    };
06.    this.stop = function(){
07.        //now i can access m_url
08.    }

The difference between this code and the previous ones, is that the public methods were declared using the prototype while now they are declared using the this keyword. The main difference is in the way the JavaScript engine execute this code. When declaring functions using the prototype, the Javascript engine creates only one instance of the function in memory and dynamically assigns the this according to the calling object. On the other hand, when declaring a method inside the object constructor, as we did in the last example, the JavaScript engine will create a copy of that function in memory for every instance that you create from the Player class. Usually this shouldn't be a big factor, but its important to know the difference.

Static Methods & Variables

Using closures and the prototype characteristic i mentioned above you can also create static methods like so:

01.function Player(url){
02.    var m_url = url;
03.    this.start = function(){
04.        //now i can access m_url
05.    };
06.    this.stop = function(){
07.        //now i can access m_url
08.    }
09.    var static_int = 0;
10.    Player.prototype.getStatic = function(){ return static_int;};
11.    Player.prototype.setStatic = function(v){ static_int = v; };
14.var p1 = new Player();
15.var p2 = new Player();
17.alert( p2.getStatic() ); //will print 100.

I hope this example shows the power of JavaScript once you understand how to shape it to whatever you need. I the next post I will show how to implement interfaces and inheritance in Javascript.
Save up to 630$ when buy new iPhone 15
Free Airdrops to Claim, Share Up to $150,000 per Project
Open tool hub for free to use by any one for every one with hundreds of tools,,,
Talk to ChatGPT by your mother language
Generate creative images automatically with AI
Render creative video automatically with AI

JavaScript theo ngày

Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web