标签:增强 log com asi 原型 spro 环境 工作 重写
function Person(name) {
this.name = name || "人"
this.sayHi = function () {
console.log("我是" + this.name)
}
}
function Teacher(name) {
this.name = name
}
Teacher.prototype = new Person()
var t1 = new Teacher("王老师")
console.log(t1.sayHi()); //我是王老师
console.log(t1.name)); //王老师
在这里我们可以看到,t1这个实例的原型继承了Person构造函数。
所以,在实例t1的原型对象里,有一个name,sayHai的方法,当t1调用sayHai的方法的时候,默认会从本身自己的属性去找,若没有找到,会去原型对象上找。
而访问name的时候,先从本身属性去找,所以会返回“王老师”,若想访问Person里的name则需要通过__proto__属性指向原型对象,再通过原型对象来访问
如:ti.__proto__.name //人
但是,这样的话,通过Teacher构造函数创建出来的实例对象t1的constructor属性值就变成构造函数Person。
这样就完成了我们的原型继承!但是要切记,原型链上的的属性值始终都是共享的。
function Person(name) {
this.name = name || "人"
this.sayHi = function () {
console.log("我是" + this.name)
}
}
Person.prototype.getName = function () {
return this.name
}
function Teacher(name) {
this.name = "1"
Person.call(this, name)
}
var t1 = new Teacher("王老师")
console.log(t1.sayHi()); //我是王老师
console.log(t1.name); //王老师
通过使用 call()方法或 apply()方法,我们实际上是在(未来将要)新创建的Teacher实例的环境下调用了 Person构造函数。
若觉得看不懂,可以通过百度搜索,bind(),call(),apply()的区别与使用,这里就不在一一细说。
在这里t1实例又无法继承Person构造函数的原型里的方法。
function Person(name) {
this.name = name || "人"
this.sayHi = function () {
console.log("我是" + this.name)
}
}
Person.prototype.getName = function () {
return "我的名字叫" + this.name
}
function Teacher(name) {
Person.call(this, name)
}
Teacher.prototype = new Person()
Teacher.prototype.constructor = Teacher
Teacher.prototype.alertName = function () {
alert(this.name)
}
var t1 = new Teacher("王老师")
var t2 = new Teacher("张老师")
console.log(t1.sayHi()); //我是王老师
console.log(t1.name); //王老师
console.log(t1.getName()); //我的名字叫王老师
console.log(t1.alertName()); //王老师
t1.getName = function () {
return "别人叫我" + this.name
}
console.log(t2.getName()); //别人叫我张老师
但是可以发现,实例 t1 如果重写了原型的属性或者方法,通过 Teacher构造函数创建的 t2实例对象,他的原型属性或方法也会跟着改变。
function createAnother(obj) {
var clone = Object(obj)
clone.sayHai = function () {
alert(this.name)
}
return clone;
}
var person = {
name: "张三",
age: 19
}
var clonePerson = createAnother(person)
clonePerson.sayHai() //张三
function inheritPrototype(Teacher, Person) {
var prototype = Object(Person.prototype)
prototype.constructor = Teacher
Teacher.prototype = prototype
}
function Person(name) {
this.name = name
this.age = 18
}
Person.prototype.sayHai = function () {
alert(this.name)
}
function Teacher(name) {
Person.call(this.name)
this.sex = "男"
}
inheritPrototype(Teacher, Person)
Teacher.prototype.sayAge = function () {
alert(this.age)
}
标签:增强 log com asi 原型 spro 环境 工作 重写
原文地址:https://www.cnblogs.com/kongyijilafumi/p/12662584.html