JavaScript里面的面向对象

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

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

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

  原理如图

原文地址:https://www.cnblogs.com/xiaobeibei26/p/6596385.html