您的位置:首页 > Web前端 > JavaScript

javascript几种方法创建function对象的异同

2011-12-04 01:52 816 查看
第一种方法:

var HelloWorld = function () {

this.name = "hello";

this.sayHello = function () {

alert(this.name);

alert(this.msg);

}

}



function HelloWorld() {

this.name = "hello";

this.sayHello = function () {

alert(this.name);

alert(this.msg);

}

}

这两种创建方法相同,都可以用prototype扩展方法和属性,必须实例化才能使用,例如:

HelloWorld.prototype = {

name2: "hello2",

sayHello2: function () {

alert(this.name2);

}

}

var obj = new HelloWorld();

obj.sayHello();

obj.sayHello2();

结果为:一次弹出hello和hello2

第二中方法:

var HelloWorld = new function () {

this.name = "hello";

this.sayHello = function () {

alert(this.name);

}

}

此种方法创建的对象是静态的,不能用prototype扩展方法和属性。但可以随时直接添加方法和属性,例如:

HelloWorld.text = "hello world";

HelloWorld.fn = function () { alert("动态添加方法"); }

HelloWorld.sayHello();

HelloWorld.fn();

第三种方法:

var HelloWorld = new Function("r","alert(Math.PI*r*r);");

此种方法会创建一个Function对象,可以有一个或多个参数,但最后一个参数必须是函数的执行代码,

函数运行时会传递给一个匿名函数执行。例如:

var obj = new HelloWorld(3);

也可以用prototype扩展方法和属性:

HelloWorld.prototype = {

name: "hello",

sayHello: function () {

alert(this.name);

}

}

var obj = new HelloWorld(3); // 调用构造函数

obj.sayHello();

第四种方法:

var HelloWorld = {

name: "hello",

sayHello: function () {

alert(this.name);

}

}

和第二种方法创建的对象类似,只是写法不同而已。创建的对象为静态,不能用prototype进行扩展

HelloWorld.msg = "javascript"; // 添加一个静态属性

HelloWorld.fn = function () { this.msg; } // 添加一个静态方法

HelloWorld.sayHello();

HelloWorld.fn();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: