JavaScript 组织函数的继续
C++ 基础--虚函数
JavaScript 组织函数的继续
在上一篇中报告了 JS 对象、组织函数以及原型形式,这篇文章来议论下 JavaScript 的继续 继续是 OO 言语中的一个最为人津津有味的观点。很多 OO 言语都支撑两种继续体式格局:接口继续和完成继续。接口继续只继续要领署名,而完成继续则继续现实的要领。如前所述,由于函数没有署名,在 ECMAScript 中没法完成接口继续。ECMAScript 只支撑完成继续,而且其完成继续主假如依托原型链来完成的。
一、运用 call 或 apply
假如有一个 "人" 对象,另有一个 "门生" 对象。
function Person(name, age) {
this.name = name
this.age = age
}
function Student(subject) {
this.subject = "语文"
}
我们怎样才能使 "人" 对象继续 "门生" 对象的属性或要领呢。第一种要领,也是最简朴的要领,运用 call 或 apply 来转变 this 指向使其挪用对象的属性或要领。
function Person(name, age) {
this.name = name
this.age = age
Student.call(this, name, age)
}
var person1 = new Person("张三", "18")
console.log(person1.subject) // 语文
二、prototype
第二种要领是运用 prototype 属性。也就是说运用 "人" 的 prototype(原型) 对象指向 Student 的实例对象,那末一切 "人" 的实例,就可以继续 "门生"了。
1、先将 Person 的 prototype 对象指向一个 Student 对象的实例
Person.prototype = new Student()
// 即是掩盖或许删除了本来的 prototype 对象的值,然后赋予一个新值。
2、把 Person 的 prototype 对象的 constructor 属性在指回 Person
Person.prototype.constructor = Person;
// 任何一个 prototype 对象都具有一个 constructor 属性,指向它的组织函数。
// 假如不加这下一行代码,Person.prototype.constructor 会指向 Student
3、每个实例也会有一个 constructor 属性,默许挪用 prototype 对象的 constructor 属性。
var person1 = new Student("张三","18");
alert(person1.constructor == Person.prototype.constructor); // true
// 因此在运转 Person.prototype = new Student() ,person1.constructor 也指向 constructor
// 所以因该手动修正 constructor 的指向
// 总代码
function Person(name, age) {
this.name = name
this.age = age
}
function Student(subject) {
this.subject = "语文"
}
Person.prototype = new Student()
Person.prototype.constructor = Person;
var person1 = new Student("张三","18");
console.log(person1.subject) // 语文
三、继续 prototype(原型)
直接继续原型,我们先修正下 Student 对象的代码,增加原型
function Student(){}
Student.prototype.project = "语文"
然后将 Person 的 prototype 对象指向 Student 的 prototype,如许就完成了继续。
Person.prototype = Student.prototype
Person.prototype.constructor = Person;
var person1 = new Student("张三","18");
console.log(person1.subject) // 语文
如许做虽然效率高,然则下级获取到的权限太重,而且还会修正 constructor 指向
Person.prototype.constructor = Person;
// 这一行代码直接把 Student.prototype.constructor 的指向给改了(Person)
四、找中心介
运用空对象,代码以下
var middle = function(){}
middle.prototype = Student.prototype;
Person.prototype = new middle();
Person.prototype.constructor = Person;
console.log(Student.prototype.constructor) // Student
由于 middle 是空对象,所以修正 Person 的 prototype 对象,就不会影响 Student 的 prototype 对象。
ASP.NET Core MVC 中实现中英文切换