1.prototype特点
- 1.1存储在
prototype
中的方法可以被对应构造函数创建出来的所有对象共享
- 1.2prototype中除了可以
存储方法
以外, 还可以存储属性
- 1.3prototype如果出现了和构造函数中
同名
的属性或者方法, 对象在访问的时候, 访问到的是构造函数
中的数据
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("sss", 34);
obj1.say(); // 构造函数中的say
console.log(obj1.currentType); // 构造函数中的type
let obj2 = new Person("zs", 44);
obj2.say(); // 构造函数中的say
console.log(obj2.currentType); // 构造函数中的type
2.prototype应用场景
prototype中一般情况下用于存储所有对象都相同的一些属性以及方法
如果是对象特有的
属性或者方法, 我们会存储到构造函数
中
3.优化使用prototype后更改的构造函数
- 当不使用prototype
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.currentType = "构造函数中的type";
this.say = function () {
console.log("构造函数中的say");
}
}
let obj1 = new Person("lnj", 34);
// obj1.say();
console.log(obj1.currentType);
console.log(Person.prototype.constructor); // Person
- 使用prototype
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
Person.prototype = {
currentType: "人",
say: function () {
console.log("hello world");
}
}
let obj1 = new Person("lnj", 34);
// obj1.say();
console.log(obj1.currentType);
console.log(Person.prototype.constructor); // Object
问题:使用prototype直接赋值属性或方法会改变原有的关系
解决方法:
注意点: 为了不破坏原有的关系, 在给prototype赋值的时候, 需要在自定义的对象中
手动的添加constructor属性
, 手动的指定需要指向谁
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
Person.prototype = {
// 注意点: 为了不破坏原有的关系, 在给prototype赋值的时候, 需要在自定义的对象中手动的添加constructor属性, 手动的指定需要指向谁
constructor: Person,
currentType: "人",
say: function () {
console.log("hello world");
}
}
let obj1 = new Person("lnj", 34);
// obj1.say();
console.log(obj1.currentType);
console.log(Person.prototype.constructor);
4.属性注意点
在给一个对象
不存在的属性
设置值的时候, 不会去原型对象中查找, 如果当前对象没有就会给当前对象新增
一个不存在的属性
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
Person.prototype = {
constructor: Person,
currentType: "人",
say: function () {
console.log("hello world");
}
}
let obj = new Person("lnj", 34);
// console.log(obj.currentType); // "人"
// console.log(obj.__proto__.currentType); // "人"
// 注意点: 在给一个对象不存在的属性设置值的时候, 不会去原型对象中查找, 如果当前对象没有就会给当前对象新增一个不存在的属性
obj.currentType = "新设置的值";
console.log(obj.currentType); // 新设置的值
console.log(obj.__proto__.currentType); // "人"