search
HomeWeb Front-endJS TutorialJavaScript minimalist introductory tutorial (2): objects and functions_javascript skills

Reading this article requires programming experience in other languages.

Simple types in JavaScript include:

1. Numbers
2. String
3.Boolean (true and false)
4.null
5.undefined

All other types are objects (let’s not be fooled by the return value of the typeof operator), for example:

1. Function
2.Array
3. Regular expression
4. Objects (objects are naturally objects)

Object Basics

In JavaScript, an object is a collection of attributes (an object is an associative array). Each attribute includes:

1. Attribute name, must be a string
2. Attribute value, which can be any value except undefined

Create an object from an object literal:

Copy code The code is as follows:

//Create an empty object through object literal {}
var empty_object = {};

Attribute name and attribute value of the object:

Copy code The code is as follows:

var stooge = {
// "first-name" is the attribute name, "Jerome" is the attribute value
"first-name": "Jerome",
// "last-name" is the attribute name, "Howard" is the attribute value
"last-name": "Howard"
};

If the attribute name is a legal identifier, the quotes can be omitted:

Copy code The code is as follows:

var flight = {
airline: "Oceanic",
Number: 815,
departure: {
IATA: "SYD",
Time: "2004-09-22 14:55",
City: "Sydney"
},
arrival: {
IATA: "LAX",
Time: "2004-09-23 10:42",
City: "Los Angeles"
}
};

Let’s look at an example of property access:

Copy code The code is as follows:

var owner = { name: "Name5566" };

owner.name; // "Name5566"
owner["name"]; // "Name5566"

owner.job; // undefined
owner.job = "coder"; // or owner["job"] = "coder";

If the attribute name is not a legal identifier, it needs to be wrapped in quotes. A property that does not exist has a value of undefined. Objects are passed by reference rather than by value:

Copy code The code is as follows:

var x = {};
var owner = x;
owner.name = "Name5566";
x.name; // x.name === "Name5566"

Here x and owner refer to the same object.

The properties of an object can be deleted using the delete operator:

Copy code The code is as follows:

delete obj.x; // Delete the x attribute of object obj

Prototype of the object

Each object is linked to a prototype object, and objects can inherit properties from the prototype object. We create an object through object literal, and its prototype object is Object.prototype object (Object.prototype object itself has no prototype object). When we create an object, we can set the prototype object of the object (we will discuss the specific setting method later). When trying to get (rather than modify) a property of an object, if the property does not exist on the object, JavaScript will try to get the property from the prototype object of the object. If the property does not exist in the prototype object, then from the prototype object The prototype object is searched, and so on, until the Object.prototype prototype object. Compared with getting attributes, when we modify a certain attribute of the object, it will not affect the prototype object.

Function Basics

In JavaScript, functions are also objects, which are linked to the Function.prototype prototype object (Function.prototype is linked to Object.prototype). The function has a property named prototype, and the type of its value is an object. This object has a property constructor, and the value of the constructor is this function:

Copy code The code is as follows:

var f = function() {}

typeof f.prototype; // 'object'
typeof f.prototype.constructor; // 'function'

f === f.prototype.constructor; // true

Functions are objects. You can use functions just like objects. That is to say, functions can be saved in variables or arrays, passed to functions as parameters, and functions can be defined inside functions. As a side note, functions have two hidden properties:

1. Function context
2. Function code

The function is created as follows:

Copy code The code is as follows:

var f = function add(a, b) {
Return a b;
}

console.log(f); // Output [Function: add]

The function name after the keyword function is optional. We formulate the function name mainly for several purposes:

1. For recursive calls
2. Used by debuggers, development tools, etc. to identify functions

Many times we don’t need a function name. A function without a function name is called an anonymous function. The parameter list is enclosed in parentheses. JavaScript does not require actual parameters and formal parameters to match, for example:

Copy code The code is as follows:

var add = function(a, b) {
Return a b;
}

add(1, 2, 3); // Actual parameters and formal parameters do not match

If there are too many actual parameters, the extra actual parameters will be ignored. If there are too few actual parameters, the value of the unassigned formal parameter will be undefined. The function must have a return value. If the return value is not specified through the return statement, the function return value is undefined.

A function and the external variables it accesses form a closure. This is the key beauty of JavaScript.

Function call

When each function is called, it will receive two additional parameters:

1.this
2.arguments

The value of this is related to the specific calling mode. There are four calling modes in JavaScript:

1. Method calling mode. If a property of an object is a function, it is called a method. If a method is called via o.m(args), this is the object o (it can be seen that this and o are only bound when the call is made), for example:

Copy code The code is as follows:

var obj = {
Value: 0,
increment: function(v) {
This.value = (typeof v === 'number' ? v : 1);
}
};
obj.increment(); // this === obj

2. Function calling mode. If a function is not a property of an object, then it will be called as a function, and this will be bound to the global object, for example:

Copy code The code is as follows:

message = 'Hello World';
var p = function() {
console.log(this.message);
}

p(); // Output 'Hello World'

This behavior is sometimes confusing. Let’s look at an example:

Copy code The code is as follows:

obj = {
Value: 0,
increment: function() {
        var helper = function() {
//Add 1 to the value in the global object
This.value = 1;
}

                // helper is called as a function
​​​​ // Therefore this is the global object
        helper();
}
};

obj.increment(); // obj.value === 0

The desired result should be:

Copy code The code is as follows:

obj = {
Value: 0,
increment: function() {
        var that = this;
        var helper = function() {
That.value = 1;
}

        helper();
}
};

obj.increment(); // obj.value === 1

3. Constructor calling mode. Functions intended to be prefixed with new are called constructors, for example:

Copy code The code is as follows:

// Test is called the constructor
var Test = function(string) {
This.message = string;
}

var myTest = new Test("Hello World");

A function can be called by adding new in front of it (such functions usually start with a capital). After adding new, an object linked to the prototype property of this function will be created, and this in the constructor will be this object.

4.apply calling mode. The apply method of the function is used to call the function, which has two parameters, the first is this, and the second is the parameter array, for example:

Copy code The code is as follows:

var add = function(a, b) {
Return a b;
}

var ret = add.apply(null, [3, 4]); // ret === 7

When the function is called, we can access a class array named arguments (not a real JavaScript array), which contains all the actual parameters, so that we can implement variable length parameters:

Copy code The code is as follows:

var add = function() {
var sum = 0;
for (var i=0; i         sum = arguments[i];
}
Return sum;
}

add(1, 2, 3, 4);

Exception

Now let’s talk about JavaScript’s exception handling mechanism. We use the throw statement to throw exceptions and the try-cache statement to catch and handle exceptions:

Copy code The code is as follows:

var add = function (a, b) {
If (typeof a !== 'number' || typeof b !== 'number') {
​​​​ // throw exception
throw {
name: 'TypeError',
                message: 'add needs numbers'
        };
}
Return a b;
}

//Catch and handle exceptions
try {
Add("seven");
// e is the thrown exception object
} catch (e) {
console.log(e.name ': ' e.message);
}

Add properties to JavaScript types

Constructors exist for most types in JavaScript:

1. The constructor of the object is Object
2. The constructor of the array is Array
3. The constructor of the function is Function
4. The constructor of string is String
5. The constructor of numbers is Number
6. The constructor of Boolean is Boolean
7. The constructor of regular expression is RegExp

We can add properties (often methods) to the prototype of the constructor to make this property available to related variables:

Copy code The code is as follows:

Number.prototype.integer = function() {
Return Math[this }

(1.1).integer(); // 1

Scope

JavaScript requires functions to build scope:

Copy code The code is as follows:

function() {
// ...
}();

An anonymous function is created and executed here. You can hide variables you don’t want to expose through scope:

Copy code The code is as follows:

var obj = function() {
//Hide value, inaccessible from outside
var value = 0;

Return {
// Only this method can modify value
increment: function() {
value = 1;
},
// Only this method can read value
         getValue: function() {
             return value;
}
};
}();

obj.increment();
obj.getValue() === 1;

Inherit

There are many ways to implement inheritance in JavaScript.
When creating an object, we can set the prototype object associated with the object. We do this:

Copy code The code is as follows:

//Create an object o whose prototype object is {x:1, y:2}
var o = Object.create({x:1, y:2});

The Object.create method is defined in ECMAScript 5. If you use ECMAScript 3, you can implement a create method yourself:

Copy code The code is as follows:

// If Object.create method is not defined
if (typeof Object.create !== 'function') {
// Create Object.create method
Object.create = function (o) {
        var F = function () {};
          F.prototype = o;
               // Create a new object, the prototype object of this object is o
          return new F();
};
}

Through the Object.create method, we perform prototype-based inheritance: a new object directly inherits the properties of an old object (compared to class-based inheritance, there is no need for the existence of a class, and the object directly inherits the object). Example:

Copy code The code is as follows:

var myMammal = {
name: 'Herb the Mammal',
Get_name: function() {
         return this.name;
},
says: function() {
          return this.saying || '';
}
};

// Inherit myMammal
var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.purr = function(n) {
var i, s = '';
for (i = 0; i           if (s) {
          s = '-';
}
        s = 'r';
}
Return s;
};
myCat.get_name = function() {
Return this.says() ' ' this.name ' ' this.says();
};

The above code is very simple, but it cannot protect private members. We can use module pattern. In the module pattern, a certain type of object is generated by a function, and the function scope is used to protect private members from external access:

Copy code The code is as follows:

// mammal function, used to construct mammal objects
var mammal = function(spec) {
// that is a constructed object
var that = {};

// Public method get_name can be accessed externally
That.get_name = function() {
// spec.name cannot be directly accessed from outside
         return spec.name;
};

// Public method says can be accessed externally
That.says = function() {
// spec.saying cannot be directly accessed from outside
          return spec.saying || '';
};

Return that;
};

//Create mammal object
var myMammal = mammal({name: 'Herb'});

//cat function, used to construct cat objects
var cat = function(spec) {
spec.saying = spec.saying || 'meow';

// cat inherits from mammal, so the mammal object is constructed first
var that = mammal(spec);

// Add public method purr
That.purr = function(n) {
        var i, s = '';
for (i = 0; i                  if (s) {
                s = '-';
            }
          s = 'r';
}
        return s;
};

// Modify the public method get_name
That.get_name = function() {
          return that.says() ' ' spec.name
' ' that.says();
         return that;
};
};

//Create cat object
var myCat = cat({name: 'Henrietta'});

In the module pattern, inheritance is achieved by calling constructors. In addition, we can also access the methods of the parent class in the subclass:

Copy code The code is as follows:

Object.prototype.superior = function(name) {
    var that = this, method = that[name];
    return function() {
        return method.apply(that, arguments);
    };
};
 
var coolcat = function (spec) {
    // 获取子类的 get_name 方法
    var that = cat(spec), super_get_name = that.superior('get_name');
    that.get_name = function(n) {
        return 'like ' super_get_name() ' baby';
    };
    return that;
};

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),