the constructor pattern

来源:互联网 发布:哑铃健身软件 编辑:程序博客网 时间:2024/06/08 19:44


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 constructorvar pers=new Person('nicholas',29);person.sayName();//nicholas//call as a functionPerson('greg',27);window.sayName();//'greg'// call in the scope of another objectvar 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()).

原创粉丝点击