the constructor pattern


function sayName(){
     alert(this.name);
}
function Person(name,age){
    this.name=name;
    this.age=age;
    this.sayName=sayName;
}
var person1=new Person('nic',29);



To create a new instance of Person,use the new operator. Calling a constructor in this manner essentially causes the following four steps to be taken:

1. create a new object

2. assign the this value of the constructor to the new object(so this points to the new object) 

3. execute the code inside the constructor(adds properties to the new object)

4. return the new object


/***************************************************************************************************/

constructor as functions

the only difference between constructor functions and other functions is the way in which they are called. Constructors are,after all,just functions; there is no special syntax to define a constructor that automatically makes it behave as such. Any function that is called with the new operate acts as a constructor, whereas any function called without it acts just as you would expect a normal function call to act.For instance, the Person() function may be called in any of the following ways:

//use as a constructor
var pers=new Person('nicholas',29);
person.sayName();//nicholas

//call as a function
Person('greg',27);
window.sayName();//'greg'

// call in the scope of another object
var o=new Object();
Person.call(o,'kristen',22);
o.sayName();//'kristen'


Remember that the this object always points to the Global object(window in web browser) when a function is called without an explicitly set this value( by being an object method or through call()/apply()).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值