<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS原型继承</title>
</head>
<body>
<!--原型继承-->
<script type="text/javascript">
//clone()函数用来创建新的类Person对象
var clone = function(obj) {
var _f = function() {};
//这句是原型式继承最核心的地方,函数的原型对象为对象字面量
_f.prototype = obj;
return new _f;
}
//先声明一个对象字面量
var Animal = {
somthing: 'apple',
eat: function() {
console.log("eat " + this.somthing);
}
}
//不需要定义一个Person的子类,只要执行一次克隆即可
var Cat = clone(Animal);
//可以直接获得Person提供的默认值,也可以添加或者修改属性和方法
console.log(Cat.eat());
Cat.somthing = 'orange';
console.log(Cat.eat());
//声明子类,执行一次克隆即可
var Someone = clone(Cat);
</script>
</body>
</html>
function getProperty(obj, prop) {
if (obj.hasOwnProperty(prop))
return obj[prop]
else if (obj.__proto__ !== null)
return getProperty(obj.__proto__, prop)
else
return undefined
}
var Point = {
x: 0,
y: 0,
print: function () { console.log(this.x, this.y); }
};
var p = {x: 10, y: 20, __proto__: Point};
p.print(); // 10 20
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
print: function () { console.log(this.x, this.y); }
};
var p = new Point(10, 20);
p.print(); // 10 20
function New (f) {
var n = { '__proto__': f.prototype }; /*第一步*/
return function () {
f.apply(n, arguments); /*第二步*/
return n; /*第三步*/
};
}
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
print: function () { console.log(this.x, this.y); }
};
var p1 = new Point(10, 20);
p1.print(); // 10 20
console.log(p1 instanceof Point); // true
var p2 = New (Point)(10, 20);
p2.print(); // 10 20
console.log(p2 instanceof Point); // true
Object.create = function (parent) {
function F() {}
F.prototype = parent;
return new F();
};
Object.create = function (parent) {
return { '__proto__': parent };
};
var Point = {
x: 0,
y: 0,
print: function () { console.log(this.x, this.y); }
};
var p = Object.create(Point);
p.x = 10;
p.y = 20;
p.print(); // 10 20
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有