javascript写类方式之四
通过前面几篇得知javascript写类无非基于构造函数
和原型
。既然这样,我们写个工具函数来写类。
/**
* $class 写类工具函数之一
* @param {Object} constructor
* @param {Object} prototype
*/
function $class(constructor,prototype) {
var c = constructor || function(){};
var p = prototype || {};
c.prototype = p;
return c;
}
嗯。工具类写好了,来组装下:用构造函数来生成类实例的属性(字段),原型对象用来生成类实例的方法。
//构造函数
function Person(name) {
this.name = name;
}
//原型对象
var proto = {
getName : function(){return this.name},
setName : function(name){this.name = name;}
}
//组装
var Man = $class(Person,proto);
var Woman = $class(Person,proto);
ok,这时候已经得到了两个类Man,Woman。并且是同一个类型的。测试如下:
console.log(Man == Woman);//true
console.log(Man.prototype == Woman.prototype);//true
创建对象看看,
var man = new Man("Andy");
var woman = new Woman("Lily");
console.log(man instanceof Man);//true
console.log(woman instanceof Woman);//true
console.log(man instanceof Person);//true
console.log(woman instanceof Person);//true
ok一切如我们所期望。但是有个问题,下面代码的结果输出false,
console.log(man.constructor == Person);//false
这让人不悦:从以上的代码看出man的确是通过Man类new出来的 var man = new Man("Andy"),那么对象实例man的构造器应该指向Man,但为何事与愿违呢?
原因就在于$class中重写了Person的原型:c.prototype = p;
好了,我们把$class稍微改写下,将方法都挂在构造器的原型上(而不是重写构造器的原型),如下:
function $class(constructor,prototype) {
var c = constructor || function(){};
var p = prototype || {};
// c.prototype = p;
for(var atr in p)
c.prototype[atr] = p[atr];
return c;
}
相关文档:
XMLHttpRequest Script Injection XHR脚本注入
Another approach to nonblocking scripts is to retrieve the JavaScript code using an XMLHttpRequest (XHR) object and then inject the script into the page. This technique involves creating an XHR object, downloading the JavaScript f ......
JavaScript中的JSON
JavaScript是为网景浏览器做页面脚本语言而实现的一种编程语言。它现在还被很多人误解是java的子集。它是一种具有类C语法和弱对象的模式语言。JavaScript完全遵守ECMAScript语言说明书第三版。
JSON是JavaScript对象文字记号的子集。由于JSON是JavaSript的子集,所以在JavaScript里, ......
2、原型方式
/**
* Person类:定义一个人,有个属性name,和一个getName方法
*/
function Person(){}
Person.prototype.name = "jack";
Person.prototype.getName = function() { return this.name;}
把类的属性(字段),方法都挂在prototype上。
造几个对象测试下:
var p1 = new Person();
var ......