运行效果:
实现代码:
<script type="text/javascript">
//实例化函数的封装及this对象的指向
function Person(n, a, p) {
this.name = n;
this.age = a;
this.msg = 'hello';
this.phone = p;
this.say = function () {
return 'The ' + this.name +
' speak: ' + this.msg +
' my age is ' + this.age +
' and my phone number is ' + this.phone;
}
}
// 每次实例化this都指向新的对象
var obj1 = new Person('chihin', 27, '13172993307');
var obj2 = new Person('lee', 26, '17607511444');
document.write(obj1.say());
document.write('<br>' );
document.write(obj2.say());
console.log(obj1.say());
console.log(obj2.say());
console.log(obj1, obj2);
</script>