search
HomeWeb Front-endJS TutorialJS object-oriented usage examples

JS object-oriented usage examples

Mar 06, 2018 pm 02:06 PM
javascriptExampleusage

An object is a collection of properties and methods. What is object-oriented? Object-oriented is a programming idea and a concept. In js, object-oriented programming is implemented through a method called prototype.

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>创建对象</title></head><body><button type="button" onclick="showInfo();">点击显示学生信息</button><script type="text/javascript">
     //创建一个学生对象
     var student=new Object();    //创建对象的属性并且赋值
    student.age=50;
    student.name="小黑";
    student.address="海淀区";    //创建对象的方法
    student.sayHello=function(){
        document.write("姓名:"+student.name+"<br/>");
        document.write("年龄:"+student.age+"<br/>");
        document.write("住址:"+this.address+"<br/>");
    }    //用户点击按钮触发的事件
    function showInfo(){
        student.sayHello(); //调用student的方法
    }    //现在只是创建了一个对象! 如果我们想创建多个 那么代码冗余!</script></body></html>

Create objects through literals

Create a student object
{Attribute 1: value 1, attribute 2: value 2, attribute 3: value 3}
json data format: It is a data conversion format
01. It is in the form of a key-value pair
02. The object is saved in {}
03. The collection is saved in []
04. Data is separated by commas, and attributes and attribute values ​​are separated by colons

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>通过字面量来创建对象</title></head><body>
     <button type="button" onclick="showInfo();">点击显示学生信息</button><script type="text/javascript">
     var student={
         age:50,
         name:"小黑",
         address:"海淀区",
        sayHello:function(){  //方法
            document.write("姓名:"+this.name+"<br/>");
            document.write("年龄:"+this.age+"<br/>");
            document.write("住址:"+this.address+"<br/>");
        }
     }    // student 我们称之为变量   =右边的{}中的数据,我们称之为 字面量!
     //用户点击按钮触发的事件
     function showInfo(){
         student.sayHello(); //调用student的方法
     }     // 问题依然存在:现在只是创建了一个对象! 如果我们想创建多个 那么代码冗余!</script></body></html>

Create multiple objects through constructors

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>通过构造函数创建多个对象</title></head><body><script type="text/javascript">
    //创建构造函数   函数名称首字母必须大写
    function Student(name,age,address){
         //声明属性并赋值
        this.name=name;        this.age=age;        this.address=address;        //设置方法
        this.sayHello=function(){
            document.write("姓名:"+this.name+"<br/>");
            document.write("年龄:"+this.age+"<br/>");
            document.write("住址:"+this.address+"<br/>");
        }
    }    //创建多个对象
    var  stu1=new Student("小黑1",50,"天堂1");    var  stu2=new Student("小黑2",51,"天堂2");    var  stu3=new Student("小黑3",52,"天堂3");  //分别调用对象的方法
    stu1.sayHello();
    stu2.sayHello();
    stu3.sayHello();  // 所有的对象都有一个constructor属性!指向了构造函数!
    document.write("stu1.constructor指向了Student:"+(stu1.constructor==Student)+"<br>");    //instanceof 判断某个对象是否属于某个类型
    document.write("stu1属于Student吗?"+(stu1 instanceof Student)+"<br>");
    document.write("stu1属于Object吗?"+(stu1 instanceof Object)+"<br>");
    document.write("stu1属于Function吗?"+(stu1 instanceof Function)+"<br>");</script></body></html>

Prototype objects

Note point:
01. All objects have a constructor attribute! Points to the constructor!
​ ​ 02. When we create a function, the function will have a prototype attribute,
This attribute points to the prototype object created through the constructor! Student.prototype
03. A prototype object is an object in memory that provides shared properties and methods for other objects!
04.The prototype attribute is only available to functions!
05. Each object has a __proto__ attribute, which points to the prototype object!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>原型对象</title></head><body><script type="text/javascript">
    /*创建一个构造函数*/
    function  Student(){}   //通过原型对象来创建对象
    Student.prototype.name;
    Student.prototype.age;
    Student.prototype.address;
    Student.prototype.sayHello=function(){
        document.write("姓名:"+this.name+"<br/>");
        document.write("年龄:"+this.age+"<br/>");
        document.write("住址:"+this.address+"<br/>");
    }    var  stu1=new Student();
    stu1.name="小白";
    stu1.age=52;
    stu1.address="天上人间";    var  stu2=new Student();
    stu2.sayHello();    // 验证每个对象都有一个__proto__属性,指向了原型对象!
    document.write(stu2.__proto__==Student.prototype);</script></body></html>

01. The prototype attribute is only available to functions!
02. Each object has a __proto__ attribute, which points to the prototype object!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>深入原型对象</title></head><body><script type="text/javascript">
    //01.验证只有函数有prototype属性
    var  a={};
    document.write(a.prototype+"<br/>");
    document.write(a.__proto__+"<br/>");    var b=function(){}
    document.write(b.prototype+"<br/>");
    document.write(b.__proto__+"<br/>");    var c=new b();    // 02.验证每个对象都有一个__proto__属性,指向了原型对象!
    document.write(c.__proto__== b.prototype);</script></body></html>

Prototype chain

Prototype chain:
01. A prototype object is an instance of another prototype object! A kitten is an example of an animal!
02. The related prototype chains progress layer by layer, forming a chain of instances and prototype objects. We call it the prototype chain!
The black cat squatting in the corner (example)
inherit
Cat class (01. Equivalent to a black cat, it is a prototype object 02. Compared to an animal, it is an instance)
inherit
Animal class (01. Prototype object of all animals 02. Instance of object)
inherit
Object (the top level of all prototype objects)
As long as it is an object, it has the __proto__ attribute, pointing to the prototype object!
question:
​ ​ ​ Object is an object!
It has __proto__ attribute!
The attribute value is null!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>原型链</title></head><body><script type="text/javascript">
        //模拟一个构造函数
          var   Student=function(){};         var stu1=new Student();
            document.write(stu1.__proto__+"<br/>"); //student
            document.write(stu1.__proto__.__proto__+"<br/>");//function
            document.write(stu1.__proto__.__proto__.__proto__+"<br/>");  //  object null
            document.write("===================================");
          document.write((stu1.__proto__===Object.prototype)+"<br/>");  //false
          document.write((Student.prototype.__proto__===Object.prototype)+"<br/>");  //true</script></body></html>

Borrow constructor

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>借用构造函数的同时传递参数</title></head><body>

   <script type="text/javascript">
         //创建Animal的构造
       function Animal(name){
         this.name=name;
       }       //创建Dog的构造
       function Dog(){
           //借用构造  传递参数
           Animal.call(this,"小黑狗");           this.age=50;
       }       //创建Cat的构造
       function Cat(){
           //借用构造
           Animal.call(this,"小猫咪");           this.health=100;
       }         //创建小狗的实例
       var dog1=new Dog();
       document.write(dog1.name);
       document.write(dog1.age);         //创建小猫咪的实例
       var cat1=new Cat();
       document.write(cat1.name);
       document.write(cat1.health);   </script></body></html>

Combined inheritance

Combined inheritance:
Sometimes called pseudo-classical inheritance, it combines the techniques of prototype chaining and borrowing constructors,
An inheritance pattern that leverages the best of both worlds uses the prototype chain to inherit prototype properties and methods.
Inheriting instance attributes is achieved by borrowing constructors

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>组合继承</title></head><body><script type="text/javascript">
    /*构造方法*/
    function  Person(name){
        this.name=name;        this.names=["hei","bai","pei"];
    }
    Person.prototype.sayHello=function(){
        alert(this.name);
    }    function  Student(name,age){
        Person.call(this,name); //继承属性  借用构造
        this.age=age;
    }
    Student.prototype=new Person();//继承了方法  原型链
    //student特有的方法
    Student.prototype.sayBey=function(){
        alert(this.name);
    }    /*创建对象*/
    var  stu=new Student("小黑黑",50);
    stu.names.push("小白白");
    document.write(stu.names+"<br/>");
    stu.sayHello();
    stu.sayBey();    var  stu1=new Student("小黑黑2",50);
    document.write(stu1.names+"<br/>");
    stu1.sayHello();
    stu1.sayBey();</script></body></html>

Related recommendations:
Detailed explanation of js object-oriented inheritance knowledge

Detailed description of JS object-oriented programming

JavaScript object-oriented design_js object-oriented

The above is the detailed content of JS object-oriented usage examples. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function