创建支持链式调用的类(构造函数+原型)

Function.prototype.method = function(name, fn){
    this.prototype[name] = fn;
    return this;
};

//构造函数+原型 创建类
var Anim = function(){};
Anim.method('starts', function(){
    console.log('starts');
}).method('ends', function(){
    console.log('ends');
});

var a = new Anim(); //注意new不能少
a.starts();
a.ends();

匿名函数创建闭包构造私有变量

var baz;
(function(){
    var foo = 10; //私有变量
    var bar = 2;
    baz = function(){ //访问私有变量的接口
        return foo * bar;
    };
})();
console.log(baz());

对象的易变性

这个没什么稀奇的,了解了原型链是怎么一回事,这个跟不不在话下。(我们可以在创建实例后添加方法和修改方法,甚至删除方法)。

var Person = function(name, age){
    this.name = name;
    this.age =age;
};

Person.method('getName', function(){
    return this.name;
}).method('getAge', function(){
    return this.age;
});
var alice = new Person('alice', 95);
var bill = new Person('bill', 30);

Person.method('getGreeting', function(){ //在创建实例后继续添加方法
    return 'Hi ' + this.getName() + '!' ;
});

alice.displayGreeting = function(){
    return this.getGreeting();
};

console.log(alice.getGreeting());
console.log(bill.getGreeting());
console.log(alice.displayGreeting());
/*bill.displayGreeting();*/

 

相关文章:

  • 2021-06-15
  • 2021-07-03
  • 2022-12-23
  • 2021-07-31
  • 2021-10-08
  • 2021-09-07
  • 2022-12-23
猜你喜欢
  • 2021-09-08
  • 2021-06-30
  • 2021-07-10
  • 2021-08-24
  • 2021-04-14
  • 2021-07-17
  • 2021-10-01
相关资源
相似解决方案