165   JS

一,new 的实现

 <html>

<body>

<script>

function person(name,age){
 this.name = name;
 this.age = age;
}

person.prototype.speak = function(word){
 console.log(word)
}


person.prototype.run = function(){
 console.log('run')
}

var one = new person('one','1');
console.log(one)
one.age;
one.name;
one.speak('hi');
one.run();

// 实现 new 的功能
function personExtend(name,age){
 var obj = {};
 obj.__proto__ = person.prototype
 obj.name = name;
 obj.age = age;
 return obj
}

var two = personExtend('two','2');

console.log(two);
two.age;
two.name;
two.speak('hi');
two.run();


</script>
</body>

</html>

二,new 做的事情

1,创建一个空对象
2,该对象的 __proto__ 指向构造函数的 prototype
3,将构造函数的实例属性赋值给该对象
4,返回该对象




Leave a Reply

Your email address will not be published. Required fields are marked *