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

Using JavaScript to imitate oop programming methods

一个新手
一个新手Original
2017-10-14 09:39:581167browse

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

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="小李"};

(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对象方可访问
    };

(3 ) Call

##

Person.ShowName(new Person());

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={};//一个类
(2) Add attributes to the class


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


alert(a.name);

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!

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