javascript
javascript对象的几种创建方式
1.工廠模式
function createBlog(name, url) {
var o = new Object();
o.name = name;
o.url = url;
o.sayUrl= function() {
alert(this.url);
}
return o;
}
var blog1 = createBlog('wuyuchang', 'http://www.jb51.net/');
?
2.構造函數模式
function Blog(name, url) {
this.name = name;
this.url = url;
this.alertUrl = function() {
alert(this.url);
}
}
var blog = new Blog('wuyuchang', 'http://www.jb51.net/');
console.log(blog instanceof Blog);
?
3. 原型模式
function Blog() {
}
Blog.prototype.name = 'wuyuchang';
Blog.prototype.url = 'http://tools.jb51.net/';
Blog.prototype.friend = ['fr1', 'fr2', 'fr3', 'fr4'];
Blog.prototype.alertInfo = function() {
alert(this.name + this.url + this.friend );
}
// 以下為測試代碼
var blog = new Blog(),
blog2 = new Blog();
blog.alertInfo(); // wuyuchanghttp://tools.jb51.net/fr1,fr2,fr3,fr4
blog2.alertInfo(); // wuyuchanghttp://tools.jb51.net/fr1,fr2,fr3,fr4
blog.name = 'wyc1';
blog.url = 'http://***.com';
blog.friend.pop();
blog2.name = 'wyc2';
blog2.url = 'http://+++.com';
blog.alertInfo(); // wyc1http://***.comfr1,fr2,fr3
blog2.alertInfo();
?
4.混合模式(原型模式 + 構造函數模式)
function Blog(name, url, friend) {
this.name = name;
this.url = url;
this.friend = friend;
}
Blog.prototype.alertInfo = function() {
alert(this.name + this.url + this.friend);
}
var blog = new Blog('wuyuchang', 'http://tools.jb51.net/', ['fr1', 'fr2', 'fr3']),
blog2 = new Blog('wyc', 'http://**.com', ['a', 'b']);
blog.friend.pop();
blog.alertInfo(); // wuyuchanghttp://tools.jb51.net/fr1,fr2
blog2.alertInfo(); // wychttp://**.coma,b
?
5.動態原型模式
function Blog(name, url) {
this.name = name;
this.url = url;
if (typeof this.alertInfo != 'function') {
// 這段代碼只執行了一次
alert('exe time');
Blog.prototype.alertInfo = function() {
alert(thia.name + this.url);
}
}
}
var blog = new Blog('wuyuchang', 'http://tools.jb51.net'),
blog2 = new Blog('wyc', 'http:***.com');
?
轉載于:https://www.cnblogs.com/weihaha0303/p/8527798.html
總結
以上是生活随笔為你收集整理的javascript对象的几种创建方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样生成分布式情况下的唯一标示?必须包含
- 下一篇: targetNamespace