<ul>
<li name="mikl">牛奶</li>
<li name="juice">果汁</li>
<li name="coffee">咖啡</li>
</ul>
<div>
<label >爱好:</label><span id="like"></span>
</div>
</body>
<script>
var ul=document.getElementsByTagName("ul")[0];
var like=document.getElementById("like")
ul.onclick=function (e) {
var target=e.target||e.srcElement //srcElement兼容ie浏览器
if(target.nodeName.toLowerCase()=="li"){
var name=target.getAttribute("name");
var factory1=new factory(name);
factory1.drinkWT(name);
}
}
var myConst={}
myConst.name={
milk:"mikl",
juice:"juice",
coffee:"coffee",
}
var juice=function (name) {
this.name=name;
}
juice.prototype={
constructor:juice,
drink:function (name) {
likeDoSomething(name)
}
}
var milk=function (name) {
this.name=name;
}
milk.prototype={
constructor:milk,
drink:function (name) {
likeDoSomething(name)
}
}
var coffee=function (name) {
this.name=name;
}
coffee.prototype={
constructor:coffee,
drink:function (name) {
likeDoSomething(name)
}
}
var other=function (name) {
constructor:other,
this.name=name;
}
other.prototype={
drink:function (name) {
likeDoSomething(name)
}
}
var factory=function (name) {
this.name=name;
}
factory.prototype={
//重新定义改写原型对象,则constructor属性则会丢失,如果没有改写原型对象,则constructor指向构造函数
constructor:factory,
drinkWT:function (obj) {
var select_obj=getobj(obj);
select_obj.drink(obj)
}
}
function getobj(obj) {
var object
switch (obj){
case myConst.name.juice:object=new juice(obj);break;
case myConst.name.coffee:object=new coffee(obj);break;
case myConst.name.milk:object=new milk(obj);break;
}
console.log(object.__proto__)//指向构造函数的原型
console.log(object.__proto__.__proto__)
console.log(object.__proto__.__proto__.__proto__)
console.log(object.constructor)
console.log(object.constructor===object.__proto__.constructor)//每一个构造函数的实例都会从构造函数的原型上继承一个constructor属性,指向构造函数
//原型链概念
/* 每个对象都会在其内部初始化一个属性,就是__proto__,当我们访问一个对象的属性 时,如果这个对象内部不存在这个属性,
那么他就会去__proto__里找这个属性,这个__proto__又会有自己的__proto__,于是就这样 一直找下去。*/
//name这里就不难理解为啥object.constructor===object.__proto__.constructor,实例化的object对象是没有constructor属性,所以它就去找object的__proto__,
//而object.__proto__又指向构造函数的原型(fun.prototype指向的原型对象),而fun.prototype指向的原型对象的constructor又指向构造函数(在重新修改原型对象时改写了原型对象的constructor的指向)
//当然在object.__proto__中找到了constructor属性,如果没有找到,它会继续找object.__proto__.__proto__,直到原型链终点
//原型链的本质在于__proto__
return object;
}
function likeDoSomething(name){
like.innerText=name;
}
</script>
转载于:https://my.oschina.net/u/3407699/blog/1505625