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()).
- the constructor pattern
- Professional JS(六-Understanding the object&&factory/constructor/prototype pattern)&enumerable
- The constructor BASE64Decoder()
- The Constructor Initializer in c++
- The constructor Date() is undefined
- The constructor Date() is undefined
- The second pattern-------Observer Pattern
- The third pattern------Decorator Pattern
- The forth pattern-----Factory Pattern
- The fifth pattern------Singleton Pattern
- The sixth pattern------------Command Pattern
- The tenth pattern---------------State Pattern
- The eleventh pattern------Proxy Pattern
- The twelfth pattern------Compound Pattern
- Constructor call must be the first statement in a constructor
- Constructor call must be the first statement in a constructor
- Constructor call must be the first statement in a constructor
- Constructor call must be the first statement in a constructor
- 数据结构:顺序结构和链式结构的数据类型定义
- ubuntu下一台mysal启动多实例
- java--经典50题part1
- python中numpy-choice函数
- Linux文件管理的链接文件问题
- the constructor pattern
- 防止sql注入方法
- JAVA的基本数据类型和引用数据类型
- java 保留字符串数字的位数,不够前面补0
- javaScript AJAX详解
- onenote发送至博客实践(CSDN)
- python selenium+beautifulSoup爬取彩票网数据
- 转载-Python下利用epd_free安装pandas
- 数据库dao中