javascript写类方式之三
取前面两种的优点:
a、用构造函数来定义类属性(字段)
b、用原型方式来定义类的方法。
就有了第三种方式。这种方式貌似采用的人较多。
3、综合构造函数/原型
/**
* Person类:定义一个人,有个属性name,和一个getName方法
* @param {String} name
*/
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
这样,即可通过构造函数构造不同name的人,对象实例也都共享getName方法,不会造成内存浪费。
但似乎这样的代码风格似乎仍然没有java的类那么紧凑,把属性,构造方法(函数),方法都包在大括号内。
public class Person {
//属性(字段)
String name;
//构造方法(函数)
Person(String name) {
this.name = name;
}
//方法
String getName() {
return this.name;
}
}
为了让js代码风格更紧凑,把挂在prototype的方法代码移到function Person的大括号内。
function Person(name) {
this.name = name;
Person.prototype.getName = function() {
return this.name;
}
}
似乎很神奇,还能这么写啊!验证一下
var p1 = new Person("Jack");
var p2 = new Person("Tom");
console.log(p1.getName());//Jack
console.log(p2.getName());//Tom
没有报错,控制台也正确输出了。说明可以这么写,呵呵。
嗯,似乎很完美。
a 、可以通过传参构造对象实例
b 、对象实例都共享同一份方法不造成内存浪费
c 、代码风格也比较紧凑
但每次new一个对象的时候都会执行
Person.prototype.getName = function() {
return this.name;
}
造成了不必要的重复的运算。因为getName方法挂在prototype上只需执行一次即可。只需稍微改造下:
function Person(name) {
this.name = name;
if(Person._init==undefined) {
alert("我只执行一次!");
Person.prototype.getName = function() {
return this.name;
}
Person._init = 1;
}
}
new两个对象,
var p1 = new Person("Andy");//第一次new会弹出'我只执行一次!'
var p2 = new Person("Lily");//以后new的对象不会再执行了
相关文档:
这个随笔其实是为了感谢清风笑给的一个提示,不仅仅是告诉我怎么判断数组,更让我有了认真读一读 《javascript权威指南》的想法。
比较和拷贝其实是一回事,代码如下:
//
//Compare object function
//
function Compare(fobj,sobj)
{
var ftype = typ ......
Dynamic Script Elements 动态脚本元素
The Document Object Model (DOM) allows you to dynamically create almost any part of an HTML document using JavaScript. At its root, the <script> element isn't any different than any other element on a page: references can be retrie ......
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 ......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
&nb ......