zoukankan      html  css  js  c++  java
  • Javascript Design Patterns

    JavaScript is a class-less language, however classes can be simulated using functions. 

    eg:

    // A car 'class'
    function Car(model) { 
        this.model = model; 
        this.color = 'silver'; 
        this.year = '2012'; 
        this.getInfo = function () {
            return this.model + ' ' + this.year; 
        }
    }

    We can then instantiate the object using the Car constructor we defined above like this: 

    var myCar = new Car('ford'); 
    myCar.year = '2010'; 
    console.log(myCar.getInfo());

    另一个例子

    var Person = function (name) { 
        this.name = name;
        this.say = function () {
            return "I am " + this.name; 
        };
    };
    
    // use the class
    var adam = new Person("Adam"); 
    adam.say(); // "I am Adam"

    上述关于类函数的做法性能不佳,原因如下:

    any time you call new Person() a new function is created in memory.

    This is obviously inefficient, because the say() method doesn’t change from one instance to the next.

    (每次new对象的时候会在内存中新建一个函数)

    The better option is to add the method to the prototype of Person 

    (比较好的方法是把方法增加到Person对象的prototype)

    Person.prototype.say = function () {
        return "I am " + this.name; 
    };

    just remember that reusable members, such as methods, should go to the prototype 

    (关于JS类必须要记住的是,可重用的成员,例如方法必须放到对象的prototype)

  • 相关阅读:
    Visual Studio中配置Beyond Compare为版本比较工具
    Restsharp常见格式的发送分析
    dex2jar反编译dex文件
    Apktool反编译apk资源文件
    远程桌面复制粘贴突然失效的问题
    C#4.0 HTTP协议无法使用TLS1.2的问题
    TFS-Git官方教程
    git 换行符问题
    NPM升级
    NodeJS笔记(一)-免安装设置
  • 原文地址:https://www.cnblogs.com/davidgu/p/3294687.html
Copyright © 2011-2022 走看看