1.prototype特点
1.1存储在prototype中的方法可以被对应构造函数创建出来的所有对象共享
构造函数function P 是被Function 创造出来的,即P是Function的对象,所以Function.prototype 有的,P能访问,但!new P创造出来的对象不能访问到Function.prototype,但能访问到Object.prototype
1.2prototype中除了可以存储方法以外, 还可以存储属性
1.3prototype如果出现了和构造函数中同名的属性或者方法, 对象在访问的时候,访问到的是构造函中的数据
2.prototype应用场景
prototype中一般情况下用于存储所有对象都相同的一些
属性以及方法
如果是对象特有的属性或者方法, 我们会存储到构造函数中
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.currentType = "构造函数中的type";
this.say = function () {
console.log("构造函数中的say");
}
}
Person.prototype = {
currentType: "人",
say: function () {
console.log("hello world");
}
}
let obj1 = new Person("lnj", 34);
obj1.say();
console.log(obj1.currentType);
let obj2 = new Person("zs", 44);
obj2.say();
console.log(obj2.currentType);
构造函数中的say
构造函数中的type
构造函数中的say
构造函数中的type
网友评论