基础代码
var Circle = { "PI":3.1415, 'area':function(r){ return this.PI * r *r; }; } console.log(Circle.area(1.0)); //直接量,最直观
稍微变体
//分步写法,新建对象,对象属性、方法赋值 var Circle = new object(); Circle.PI = 3.1415; Circle.Area = function(r){ return this.PI * r * r; } console.log(Circle.Area(1.0));
再次变体
//工厂模式,稍微变体 var Circle = function(){ var obj = new object(); obj.PI = 3.1415; obj.area = function(r){ return this.PI * r * r; } return obj; } var c = new Circle(); console.log(c.area(1.0));
下面是原型和构造的混合,加入了静态属性的访问
function Circle(r){ this.r = r; } Circle.PI = 3.1415; Circle.prototype.area = function(){ return Circle.PI * this.r * this.r; } var c = new Circle(1.0); console.log(c.area());
继承
function Person(){ var name = "default"; return { getName : function(){ return name; }, setName : function(newName){ name = newName; } } }; var p = new Person(); p.setName("Tom"); alert(p.getName()); var Jack = function(){}; //继承自Person Jack.prototype = new Person(); //添加私有方法 Jack.prototype.Say = function(){ alert("Hello,my name is Jack"); }; var j = new Jack(); j.setName("Jack"); j.Say(); alert(j.getName());