`
ricoyu
  • 浏览: 9982 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

纠错 JavaScript 的几个 tip

阅读更多
[url=http://www.iteye.com/topic/6122]JavaScript 的几个 tip[/url] 一贴中有一处错误, 未免误导大家, 现奉上我的观点:
引用
1、JavaScript 中的继承
在 JavaScript 中实现继承的方法是:将子类的 prototype 属性设置为父类的对象。
例如,我有一个 Basket 类,继承 Hashtable 类:

Java代码 
1.Basket.prototype = new Hashtable();;  
2.Basket.prototype.constructor = Basket;  
Basket.prototype = new Hashtable();;
Basket.prototype.constructor = Basket;

如果不写上面第二句,以后 typeof 一个 Basket 的对象获得的就是 Hashtable 了。

最后一句是错误的, 请看我的测试:
<html>
<head>

</head>
<body>
<div id='display'></div>
<script language="javascript">
function Person(name){
  this.name = name;
}

function Man(){
}
var me = new Man();
dwr('me.constructor before change prototype:'+me.constructor);
dwr('typeof me      before change prototype:'+typeof me);
Man.prototype = new Person();
dwr('me.constructor after change prototype:'+me.constructor);
dwr('typeof me      after change prototype:'+typeof me);
var you = new Man();
dwr('create you and you.constructor after change prototype:'+you.constructor);
dwr('create you and typeof you after change prototype:'+typeof you);

function dwr(s){
  var display = document.getElementById('display');
  display.innerHTML+=s+'<br/>';
}
</script>
</body>
</html>


运行结果:
me.constructor before change prototype:function Man(){ }
typeof me before change prototype:object
me.constructor after change prototype:function Man(){ }
typeof me after change prototype:object
create you and you.constructor after change prototype:function Person(name){ this.name = name; }
create you and typeof you after change prototype:object

结论:
改变函数的prototype对象并不影响typeof的结果,只影响obj.constructor的结果。
obj.constructor, 该constructor属性是属于该函数的prototype对象的,
或者这么说, 当你创建一个函数Person时, 该函数就会有一个prototype对象, 该prototype对象中持有一个constructor属性来指向这个函数, 所以当你创建这个函数的对象obj后, 有这样的关系:
obj.constructor = Person.prototype.constructor = Person

但是当改变函数的prototype对象后:
var person = new Person();
Man.prototype = person;
var other = new Man();
那么:
other.constructor == Man.prototype.constructor;
Man.prototype此时是Person的实例, 即
Man.prototype == person;
所以有:
other.constructor == Man.prototype.constructor == person.constructor == Person.prototype.constructor == Person

以下又是测试:)
<html>
<head>

</head>
<body>
<div id='display'></div>
<script language="javascript">

function Person(){};
function Man(){};
var person = new Person();
Man.prototype = person;
var other = new Man();


dwr(other.constructor == Man.prototype.constructor);
dwr(Man.prototype.constructor == person.constructor);
dwr(person.constructor == Person.prototype.constructor);
dwr(Person.prototype.constructor == Person);
dwr(other.constructor == Person);


function dwr(s){
  var display = document.getElementById('display');
  display.innerHTML+=s+'<br/>';
}
</script>
</body>
</html>


结果:
true
true
true
true
true
分享到:
评论
1 楼 gwj41 2011-03-09  
沙发,学习一下,好文章

相关推荐

Global site tag (gtag.js) - Google Analytics