标准用法:

function Sprite(){
    //函数内容部设置属性
    this.name='shimily';
} 
//原型上设置方法
Sprite.prototype.show=function(){
    console.log(this.name);
}
//【尽量不要在原型上面添加公共属性
//公共的属性或常量可以在原型上面设置
Sprite.prototype.PI=3.1415926;var s = new Sprite();
s.show();

 改进用法:

改进用法一:*************************

function Sprite2(name,age){
    //函数内容部设置属性
    this.name=name;
    this.age=age;
} 
//原型上设置方法
Sprite2.prototype.show=function(){ console.log(this.name); } var s2 = new Sprite2('shimily1314',20); s2.show();

 

改进方法二:*******************

function Sprite3(options){
    //函数内容部设置属性
    this.name=options.name;
    this.age=options.age;
} 
//原型上设置方法
Sprite3.prototype.show=function(){
    console.log(this.name);
}
var s3 = new Sprite3({
    name:'shimilygood',
    age:20});
 s3.show();

 

最终常用方法:***************

    function Sprite4(options){
        //函数内容部设置属性
        this.__init(options);
    } 

    Sprite4.prototype.__init=function(options){
        this.name=options.name;
        this.age=options.age;
        this.color=options.color;
    }
    //原型上设置方法
    Sprite4.prototype.show=function(){
        console.log(this.name);
    }

    var s4 = new Sprite4({
        name:'shimilygood123',
        age:20
    });
    s4.show();

【最好、最常用】

最终【优化版】常用方法:***************

function Sprite5(options){
        //函数内容部设置属性
        this.__init(options);
    } 

    Sprite5.prototype={
        __init:function(options){  //只允许内部调用的方法【仅内部调用】
            this.name=options.name;
            this.age=options.age || 20;
            this.color=options.color || 'red';
            console.log(this.name);
        },
        show:function(ele){   //[可以不加参数]外部可以调用的方法不使用下划线
            console.log(this.name + ele);
        }

    };
    var s5 = new Sprite5({
        name:'shimilygoodabc',
        age:20
    });
    s5.show('yang');

 

给心灵一个纯净空间,让思想,情感,飞扬!