javascript - js原型小问题
本文介绍了javascript - js原型小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
function Tt(){
this.name = "hello";
this.age = 88;
if(typeof this.say != "function"){
Tt.prototype = {
constructor: Tt,
say: function(){
return this.name;
}
};
}
}
var t = new Tt();
**console.log(t.say()); // Uncaught TypeError: Object #<Tt> has no method 'say' 这里为什么访问不到方法???**
// 如果这么做
function Tt(){
this.name = "hello";
this.age = 88;
if(typeof this.say != "function"){
Tt.prototype.say = function(){
return this.name;
}
}
}
var t = new Tt();
**console.log(t.say()); // 这样就没有问题!**
小白,不知道为什么这样??希望帮忙解释一下~
解决方案
What happens when a constructor is called? When new Vehicle() is called, JavaScript does four things:
It creates a new object.
It sets the constructor property of the object to Vehicle.
It sets up the object to delegate to Vehicle.prototype.
It calls Vehicle() in the context of the new object.
这篇关于javascript - js原型小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文