使用隐藏的new来创建对象_jquery

WBOY
Release: 2016-05-16 18:08:52
Original
1119 people have browsed it

很多时候我们是这样写类,然后使用new创建对象的。

复制代码代码如下:

function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype={
setName : function(n){this.name=n;},
getName : function(){return this.name;}
}
var p = new Person('jack',25);

改成这样的
复制代码代码如下:

function Person(name,age){
//条件改为(this==window)或(this==self)或(this.constructor!=Object)
if(!this.setName){
return new Person(name,age);
}
this.name=name;
this.age=age;
}
Person.prototype={
setName : function(n){this.name=n;},
getName : function(){return this.name;}
}
var p = Person('jack',25);

注意该类较最上面的写类方式中多了以下
复制代码代码如下:

if(!this.setName){
return new Person(name,age);
}

好,创建类的实例(对象)方式也变成了如下
复制代码代码如下:

var p = Person('jack',25);

这种创建方式(函数调用)较上面的少了“new_”,new和空格,实际上是在类内部new了。而这样方式每次创建对象可以减少4个byte。
如果把类内部的if判断条件换成非prototype上的属性,如this.name。程序会提示出错:too much recursion
复制代码代码如下:

function Person(name,age){
if(!this.name){
return new Person(name,age);
}
this.name=name;
this.age=age;
}
Person.prototype={
setName : function(n){this.name=n;},
getName : function(){return this.name;}
}
var p = Person('jack',25);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!