javascript面向对象特性代码实例_javascript技巧
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript面向对象特性代码实例_javascript技巧,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3067字,纯文字阅读大概需要5分钟。
内容图文
![javascript面向对象特性代码实例_javascript技巧](/upload/InfoBanner/zyjiaocheng/322/ed63d3f22b2748608c74f695c29e6506.jpg)
方法一:
function sth(a) // 构造函数
{
this.a = a;
this.fun = output; // 成员函数
}
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参数顺序一定要对
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
优点:可以实现多继承(多调用call就好)
缺点:
· 必须以构造函数方式使用
· 使用instanceof运算符运算此类继承结果为false
方法二:
{
}
A.prototype.x = 1;
function B()
{
}
B.prototype = new A(); // 不能带参数!
B.prototype.y = 2;
B.prototype.print = function()
{
document.write(this.x, ", ", this.y, "
");
}
var b = new B();
b.print();
document.write(b instanceof A); // 输出true
缺点:
· 不能实现多继承
· 构造函数不带参数
Tips
通常使用混合模式,两者一起用
function A(x)
{
this.x = x;
}
A.prototype.printx = function() // 写到A类里面this.printx = function....也是可以的,下同
{
document.write(this.x, "
");
}
function B(x, y)
{
A.call(this, x);
this.y = y;
}
B.prototype = new A(); // 不能带参数!
B.prototype.printxy = function()
{
document.write(this.x, ", ", this.y, "
");
}
var b = new B(1, 2);
b.printx(); // 输出1
b.printxy(); // 输出1, 2
document.write(b instanceof A); // 输出true
三、类似静态成员函数的使用
{
this.a = a;
}
sth.fun = function(s)
{
document.write(s.a);
}
var s = new sth(2);
sth.fun(s); // 输出2
四、对象的释放
obj = null; // 取消引用,会自动进行垃圾回收;如果需要根本释放此对象,要将它的所有引用都赋值为null
五、函数对象
v(1, 2); // 将会输出3
六、回调函数
{
func(arg);
}
function fun(arg)
{
document.write(arg);
}
//callback(func, "sb"); // 这种做法不行
var func = new Function("arg", "fun(arg);");
// 当然也可以把func(arg)换成具体的执行代码,
// 但是函数代码庞大了就最好这样做了
callback(func, "sb");
七、函数的重载
{
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);
八、利用函数闭包实现有“静态变量”的函数
{
var v = 1;
function fun2()
{
++v;
document.write(v);
document.write("
");
return v;
}
return fun2;
}
var func = fun();
func(); // 输出2
func(); // 输出3
func(); // 输出4
内容总结
以上是互联网集市为您收集整理的javascript面向对象特性代码实例_javascript技巧全部内容,希望文章能够帮你解决javascript面向对象特性代码实例_javascript技巧所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。