JavaScript:json方式的面向对象、继承、引用
json中可以放任何格式的变量,数字、字符串甚至函数。下面是一个json面向对象的写法。函数c返回a和b相加的结果。this表示该json对象。
<!DOCTYPE html>
<html>
<head>
<title>json面向对象</title>
<script type="text/javascript">
var json = {
a:12,
b:12,
c:function(){
alert('a+b=:'+(this.a+this.b));//this指的是json
}
};
alert(json.c());
</script>
</head>
<body>
</body>
</html>
下面是一个继承的小例子,关键在于call的使用,A.call(this)之后,将new出来的B作为this传给A,于是A中的this都被new出来的B替换掉,从而完成B对A的继承。B.prototype=A.prototype,该句代码将A的所有方法都赋给B。
<!DOCTYPE html>
<html>
<head>
<title>继承</title>
<script type="text/javascript">
function A(){
this.abc = 12;
}
A.prototype.show = function(){
alert(this.abc);
}
//继承属性
function B(){
//this->new B()
A.call(this);
}
//继承方法
B.prototype = A.prototype;
var obj = new B();
obj.show();
</script>
</head>
<body>
</body>
</html>
再来看引用。在下面这个例子中,B.prototype=A.prototype之后,给B加上一个方法,按理说对象A不能调用。但是实际上,A可以调用这个新加的方法,因为B.prototype=A.prototype实际上是将B.prototype和A.prototype指向了同一块内存地址,给B加,相当于给A加。
<!DOCTYPE html>
<html>
<head>
<title>引用</title>
<script type="text/javascript">
function A(){
this.abc = 12;
}
A.prototype.show = function(){
alert(this.abc);
}
//继承属性
function B(){
//this->new B()
A.call(this);
}
//继承方法
B.prototype = A.prototype;
B.prototype.add = function(){
alert('本来只属于B,却被A调用了');
}
var obj = new B();
var objA = new A();
objA.add();
</script>
</head>
<body>
</body>
</html>
下面再举一个引用的简单例子。
<!DOCTYPE html>
<html>
<head>
<title>引用</title>
<script type="text/javascript">
var arr1 = [1,2,3,4];
var arr2 = arr1;
arr2.push(5);
alert(arr1+"\n"+arr2);
</script>
</head>
<body></body>
</html>


浙公网安备 33010602011771号