Home > Web Front-end > JS Tutorial > Using JavaScript to imitate oop programming methods

Using JavaScript to imitate oop programming methods

一个新手
Release: 2017-10-14 09:39:58
Original
1245 people have browsed it

First,

First, use the keyword function to define a class

function Shape1(ax,ay) {//此时将function看成声明类的标志
    var x=0;
    var y=0;
    var  init=function () {//构造函数   对内部的变量赋值
        x=ax;
        y=ay;
    }
init();//构造函数的调用
     this.getX=function () {//this声明公有函数   var 声明私有   get方法
      return x;
    }
}
Copy after login

Then, the instantiation + call of the object

Second,

Static properties and static methods

Static methods in JavaScript act on classes rather than objects.

First, For classes declared using function

(1) First, define a class

function Person() {this.Name="小李"};
Copy after login

(2) Then, add static variables and static methods to the class

 Person.age=0;
    Person.ShowName=function (obj) {
        console.log(obj.Name)//此时的Name是Person对象类下面全局变量,需要Person对象方可访问
    };
Copy after login

(3 ) Call

##

Person.ShowName(new Person());
Copy after login

Summary: First have the class, then add static members ,

Person is a class that can be instantiated. There are static members below that need to be instantiated. In order to access

2. Classes (objects) without function declarations --Simple class

(1) First there is a class

##

var a={};//一个类
Copy after login
(2) Add attributes to the class


a["name"]="1";//添加属性
Copy after login
(3) Call


alert(a.name);
Copy after login

The above is the detailed content of Using JavaScript to imitate oop programming methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template