(轉載請註明出處)(๑•ᴗ•๑)
複製代碼
首先準備一個構造函數(後幾個皆以此爲例)函數
function Person() {
this.name = 'person',
this.age = 18
}
Person.prototype.eat = function () {}
複製代碼
function Student() {}
Student.prototype = new Person
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的性能
{
__proto__: Student.prototype {
name: 'person',
age: 18,
__proto__: Person.prototype {
eat: function () {},
__proto__: Object.prototype
}
}
}
複製代碼
優勢: 使用簡單,好理解ui
缺點: 原型鏈多了一層,而且這一層沒什麼用this
function Student() {
Person.call(this)
}
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的spa
{
name: 'person',
age: 18,
__proto__: Student.prototype {
constructor: Student,
__proto__: Object.prototype
}
}
複製代碼
優勢: 直接把屬性變成本身的了prototype
缺點: 沒有父類原型上的東西code
function Student() {
Person.call(this)
}
Student.prototype = new Person
}
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的cdn
{
name: 'person',
age: 18,
__proto__: new Person {
name: 'person',
age: 18,
__proto__: Person.prototype {
eat: function () {},
constructor: Person,
__proto__: Object.prototype
}
}
}
複製代碼
優勢: 屬性繼承來變成本身的,原型也繼承過來了blog
缺點: 第一層原型沒用,繼承的原型多走一步繼承
function Student() {
var p = new Person
for (var key in p) {
Student.prototype[key] = p[key]
}
}
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的
{
__proto__: Student.prototype {
name: 'person',
age: 18,
eat: function () {},
constructor: Student,
__proto__: Object.prototype
}
}
複製代碼
優勢: 屬性和方法都繼承來放在我本身的原型上了
缺點: for in 循環,至關消耗性能的一個東西
function Student() {
this.gender = '男'
var p = new Person
return p
}
Student.prototype.fn = function () {}
var s = new Student
複製代碼
這裏很明顯,此時直接獲得的是 Person 的實例,this.gender
和fn()
不會存在在s中
優勢: 完美的繼承了屬性和方法
缺點: 根本沒有本身的東西了
function Student() {
Person.call(this)
}
Student.prototype.fn = function () {}
Student.prototype = Person.prototype
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的
{
name: 'person',
age: 18,
__proto__: Person.prototype {
eat: function () {},
constructor: Person,
__proto__: Object.prototype
}
}
複製代碼
優勢:原型的東西不須要多走一步
缺點: 沒有本身的原型
function Student() {
Person.call(this)
}
(function () {
function Abc() {}
Abc.prototype = Person.prototype
Student.prototype = new Abc
})()
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的
{
name: 'person',
age: 18,
__proto__: new Abc {
__proto__: Person.prototype {
eat: function () {}
}
}
}
複製代碼
優勢: 屬性繼承來是本身的,方法也繼承來了,組合式繼承的中間那個環節多餘的屬性沒有了
缺點: 就是多了一個 空環,致使我訪問繼承的方法的時候要多走一步
function Student() {
Person.call(this)
}
(function () {
var obj = Person.prototype
for (var key in obj) {
Student.prototype[key] = obj[key]
}
})()
var s = new Student
複製代碼
此時在控制檯中查看S裏是這樣的
{
name: 'person',
age: 18,
__proto__: Student.prototype {
constructor: Student,
eat: function () {},
__proto__: Object.prototype
}
}
複製代碼
優勢: 屬性原型都有了,沒有多餘的空環,
constructor
直接指向本身
缺點:
for in
循環。而後就沒有缺點~~~(由於是自創的hhh)
復聯四你看了嗎?被劇透了嗎-。-好氣喲
複製代碼