日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

javascript对象的几种创建方式

發布時間:2025/7/14 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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对象的几种创建方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。