基于已有对象扩充其属性和方法
工厂方式
构造函数方式
原型(“prototype”)方式
动态原型方式
一,基于已有对象扩充其属性和方法
<script type="text/javascript">
var object = new Object();
object.name = "zhangsan";
object.sayName = function(name)
{
this.name = name;
alert(this.name);
}
object.sayName("lisi");
</script>
二,工厂方式
function createObject()
{
var object = new Object();
object.username = "zhangsan";
object.password = "123";
object.get = function()
{
alert(this.username + ", " + this.password);
}
return object;
}
var object1 = createObject();
var object2 = createObject();
object1.get();
-
改进:采用带参数的构造方法:
function createObject(username, password)
{
var object = new Object();
object.username = username;
object.password = password;
object.get = function()
{
alert(this.username + ", " + this.password);
}
return object;
}
var object1 = createObject("zhangsan", "123");
object1.get();
三,构造函数方式
function Person()
{
//在执行第一行代码前,js引擎会为我们生成一个对象
this.username = "zhangsan";
this.password = "123";
this.getInfo = function()
{
alert(this.username + ", " + this.password);
}
//此处有一个隐藏的return语句,用于将之前生成的对象返回
//只有在后面用new的情况下,才会出现注释所述的这两点情况
}
//生成对象
var person = new Person();//用了new
person.getInfo();
-
改进,带有参数
function Person(username, password)
{
this.username = username;
this.password = password;
this.getInfo = function()
{
alert(this.username + ", " + this.password);
}
}
var person = new Person("zhangsan", "123");
person.getInfo();