javascript面向對象特性代碼實例
一、基本的類的使用
方法一:
function sth(a) // 構造函數(shù)
{
this.a = a;
this.fun = output; // 成員函數(shù)
}
function output(a, b, c)
{
document.write(this.a);
}
//調用
var s = new sth(250);
s.fun(1, 2, 3);
ouput(1, 2, 3); //如果output在sth之前就是錯的
方法二:
{
this.a = a;
this.output = function()
{
document.write(this.a);
}
}
var s = new sth(2);
s.output(); // 輸出2
二、繼承
方法一:
{
this.x = x;
}
function B(x, y)
{
// 方法1
/*
this.construct = A;
this.construct(x);
delete this.construct;
*/
// 方法2
//A.call(this, x);
// 方法3
A.apply(this, new Array(x)); // 亦可A.apply(this, arguments), 不過arguments參數(shù)順序一定要對
this.y = y;
this.print = function()
{
document.write("x = ", x,
", y = ", y);
}
}
var b = new B(1, 2);
b.print();
alert(B instanceof A); // 輸出false
優(yōu)點:可以實現(xiàn)多繼承(多調用call就好)
缺點:
· 必須以構造函數(shù)方式使用
· 使用instanceof運算符運算此類繼承結果為false
方法二:
{
}
A.prototype.x = 1;
function B()
{
}
B.prototype = new A(); // 不能帶參數(shù)!
B.prototype.y = 2;
B.prototype.print = function()
{
document.write(this.x, ", ", this.y, "<br>");
}
var b = new B();
b.print();
document.write(b instanceof A); // 輸出true
缺點:
· 不能實現(xiàn)多繼承
· 構造函數(shù)不帶參數(shù)
Tips
通常使用混合模式,兩者一起用
function A(x)
{
this.x = x;
}
A.prototype.printx = function() // 寫到A類里面this.printx = function....也是可以的,下同
{
document.write(this.x, "<br>");
}
function B(x, y)
{
A.call(this, x);
this.y = y;
}
B.prototype = new A(); // 不能帶參數(shù)!
B.prototype.printxy = function()
{
document.write(this.x, ", ", this.y, "<br>");
}
var b = new B(1, 2);
b.printx(); // 輸出1
b.printxy(); // 輸出1, 2
document.write(b instanceof A); // 輸出true
三、類似靜態(tài)成員函數(shù)的使用
{
this.a = a;
}
sth.fun = function(s)
{
document.write(s.a);
}
var s = new sth(2);
sth.fun(s); // 輸出2
四、對象的釋放
obj = null; // 取消引用,會自動進行垃圾回收;如果需要根本釋放此對象,要將它的所有引用都賦值為null
五、函數(shù)對象
v(1, 2); // 將會輸出3
六、回調函數(shù)
{
func(arg);
}
function fun(arg)
{
document.write(arg);
}
//callback(func, "sb"); // 這種做法不行
var func = new Function("arg", "fun(arg);");
// 當然也可以把func(arg)換成具體的執(zhí)行代碼,
// 但是函數(shù)代碼龐大了就最好這樣做了
callback(func, "sb");
七、函數(shù)的重載
{
switch (arguments.length)
{
case 1:
document.write(arguments[0]);
break;
case 2:
document.write(arguments[0] + arguments[1]);
break;
default:
document.write("ERROR!");
break;
}
}
fun(1);
fun(1, 2);
八、利用函數(shù)閉包實現(xiàn)有“靜態(tài)變量”的函數(shù)
{
var v = 1;
function fun2()
{
++v;
document.write(v);
document.write("<br>");
return v;
}
return fun2;
}
var func = fun();
func(); // 輸出2
func(); // 輸出3
func(); // 輸出4
相關文章
contains和compareDocumentPosition 方法來確定是否HTML節(jié)點間的關系
一個很棒的 blog 文章,是 PPK 兩年前寫的,文章中解釋了 contains() 和 compareDocumentPosition() 方法運行在他們各自的瀏覽器上。2011-09-09微信小程序Page中data數(shù)據(jù)操作和函數(shù)調用方法
這篇文章主要介紹了微信小程序Page中data數(shù)據(jù)操作和函數(shù)調用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05javascript中RegExp保留小數(shù)點后幾位數(shù)的方法分享
文章介紹一篇關于javascript中RegExp保留小數(shù)點后幾位數(shù)方法,有需要了解的朋友可以參考一下2013-08-08layer.open回調獲取彈出層參數(shù)的實現(xiàn)方法
今天小編就為大家分享一篇layer.open回調獲取彈出層參數(shù)的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09