您的位置:首页 > Web前端 > JavaScript

js中的继承

2016-07-27 11:19 211 查看
1.拷贝继承

2.类继承

3.原型继承

原型继承例子:

<script>
function inherit(p){
if(p==null) throw TypeError();
if(Object.create) return Object.create(p);
var t= typeof p;
if(t!=="object" && t!=="function") throw TypeError();
function f(){};
f.prototype = p;
return new f();
}

var o = {mm:9};
o.x = 1;
o.prototype.logo=function(){                         //why 不行!!!报错
return 'tea';
};
var p = inherit(o);
p.y = 2;
var q = inherit(p);
q.z = 3;
var s = q.toString();
q.mm = 5;
console.log(q.hasOwnProperty('mm'));
console.log(p.hasOwnProperty('mm'));

console.log(s);
console.log(q.x);              //继承了o.x;
console.log(q.logo());

console.log(q.age);               //访问不存在的属性:undefind
console.log(qq.age.n);            //访问不存在的对象,会报错 Uncaught ReferenceError: qq is not defined
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 继承