举个栗子,我们首先声明一个函数Student():
function Student(name){
this.name = name;
this.hello = function(){
alert(`Hello,${this.name}`);
}
}这个函数包含一个属性name和一个方法hello。
在JavaScript中,可以通过new关键字来调用Student函数(不写new就是一个普通函数,写new就是一个构造函数),并且返回一个原型指向Student.prototype的对象,如下所示:
var xiaoming = new Student("xiaoming");
alert(xiaoming.name); // xiaoming
xiaoming.hello(); // Hello,xiaoming如果我们想确认一下我们的设想对不对,就会希望去比较一下xiaoming.prototype和Student.prototype是否相等。
但是xiaoming没有prototype属性,不过可以用__proto__来查看。接下来我们就用这些属性来查看xiaoming,Student,Object之间的原型链:
document.onreadystatechange = function(){
// interactive表示文档已被解析,但浏览器还在加载其中链接的资源
if(document.readyState === "interactive"){
var xiaoming = new Student("xiaoming");
alert(xiaoming.name);
xiaoming.hello();
console.log("xiaoming.__proto__:");
console.log(xiaoming.__proto__);
console.log("Student.prototype:");
console.log(Student.prototype);
console.log("xiaoming.__proto__ === Student.prototype:" + xiaoming.__proto__ === Student.prototype);
console.log("Student.prototype.constructor:" + Student.prototype.constructor);
console.log("Student.prototype.prototype:" + Student.prototype.prototype);
console.log("Student.prototype.__proto__:");
console.log(Student.prototype.__proto__);
console.log(Object.prototype);
console.log("Student.prototype.__proto__ === Object.prototype:" + Student.prototype.__proto__ === Object.prototype);
}
}
Copyright © 2019- huatuo6.cn 版权所有 赣ICP备2024042791号-9
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务