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

第一种方法:
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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值