首页 > JavaScript关于继承原型,为什么显示不正确??

JavaScript关于继承原型,为什么显示不正确??

下面建立的函数为什么一定要用prototype访问属性或方法,可是书上可以直接访问属性或方法的??

<script>
function supertype()
{this.property=true;}
supertype.prototype.func=function(){return 11;}

function supera(){}

supera.prototype=new supertype();//继承于supertype()

x=new supera();   

alert(supera.property);//显示undefined,应该显示true??
alert(supera.func());//显示对象不支持func方法,应该显示11??
alert(supera.prototype.property);//显示true
alert(supera.prototype.func());//显示11

alert(supertype.property);//显示undefined,这里没显示错吧??
alert(supertype.func());//对象不支持"func"属性或方法,应该显示11??
alert(supertype.property);//显示true
alert(supertype.prototype.func());//显示11
</script>

这个和面向对象没多大关系,是js的基础。 这个属于原型继承的范畴。在js里面使用的很少。 你可以看一看我写的那一
js痛点之继承

function supertype()
{this.property=true;}
supertype.prototype.func=function(){return 11;}

function get(){}

get.prototype=new supertype();//继承于supertype()

x=new get();   

console.log(x.property);//这里显示的是true
console.log(x.func());//显示的是11
//这里实例是没有prototype属性的,只有__proto__的隐藏属性,而且只能在浏览器中存在
console.log(x.__proto__.property);// 显示true
console.log(x.__proto__.func());//显示11
//下面都是正确的
【热门文章】
【热门文章】