1、JavaScript里面没有类,但是利用函数可以起到类似的作用,例如简单的构造方法,跟Python差别不大

    function f1(mame,age){
        this.Name = name;
        this.Age=age; //这是个构造方法,相当于Python类里面的self
        this.Func=function () {
            return this.Name + this.Age;
        };//函数是保存在每个对象里面的

    
    }

    obj1 = new f1('jay',18);
    obj2 = new f1('bob',18);
    obj3 = new f1('peter',18);
    obj4 = new f1('alex',18);

JavaScript里面的面向对象

 

 

 

  为了合理使用内存,将类里面的方法放在类里面而不是对象里面,可以这样设置

    function f1(name,age){
        this.Name = name;
        this.Age=age; //这是个构造方法,相当于Python类里面的self

    }
        f1.prototype={
            Func:function () {
                return this.Name + this.Age
            }
        };
//        f1.prototype.Func=function () {
//            
//        }两种方法都可以



    obj1 = new f1('jay',18);
    ret = obj1.Func();
    console.log(ret);

  原理如图

JavaScript里面的面向对象

 

相关文章:

  • 2021-12-14
  • 2021-08-16
猜你喜欢
  • 2021-08-27
  • 2021-12-09
  • 2021-12-06
  • 2022-12-23
  • 2021-10-02
  • 2021-05-21
相关资源
相似解决方案