My Octopress Blog

A blogging framework for hackers.

JavaScript Simulate Oop(js中的面向对象编程)

| Comments

js中,除了nullundefined,所有的都是对象.主要对Function对象使用new操模拟面向对象的一些特性

1.在子类中调用父类方法, 主要使用call方法来带入this

模拟extend方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//extend实现继承
Function.prototype.extend = function(parent) {
  var child = this;
  child.prototype = parent;
  child.prototype.constructor = child;
}

var Animal = {
  name: 'noname',
  speak: function() {
    return this.name + " say Hi!";
  }
};

var Rabbit = function(name) {
  if (name) this.name = name;

  this.speak = function() {
    return Animal.speak.call(this);
  };
}

Rabbit.extend(Animal);
var rabbit1 = new Rabbit("Joy");
console.log(rabbit1.speak());//Joy say Hi!

2.javascript中的静态方法

既然js中都是对象的概念,那么只要直接对Function对象添加属性,而不是通过,this或者prototype来指定属性,就可以实现静态变量或者静态方法

1
2
3
4
5
6
7
8
9
function Robbot(){
}
Robbot.name1 = "Sky";
Robbot.sayHi = function hello() {
    return this.name1;
}
console.log(Robbot.name);//Robbot
console.log(Robbot.sayHi());//Sky
console.log(Robbot.sayHi.name);//''

Function.name 会返回function的name, 且是readonly的属性

Comments