js類的繼承與建立

2021-10-02 20:23:12 字數 1249 閱讀 3709

類的建立,new 乙個function ,在這個function的prototype裡面增加屬性和方法。

function

a(food)

a.prototype.

eat=

function

(food)

原型繼承:

student.prototype=

newperson()

;student.prototype.constructor=student;

缺點:無法設定建構函式的引數

借用建構函式繼承:

function

fn(x,y)

var o=

;//bind方法 改變函式的this 並且返回乙個新的函式 不呼叫函式

var f=fn.

bind

(o,1,2

);f(

);//call函式 改變函式中的this 直接呼叫函式

fn.call

(o.2.3

);

function

person

(name,age,***)

function

student

(name,age,***,score)

var s1=

newstudent

('zs',13

,'男'

,100);

console.

dir(s1)

;

缺點:只可繼承屬性,不能繼承方法。

組合繼承:

繼承方法與屬性綜合:

綜合call方法和

student.prototype=person.prototype;

student.prototype.constructor=student;

但只有乙個物件指向,即student增加乙個方法,person也增加乙個同樣的方法。若想子型別只有某個方法而父型別沒有,則結合以下:

student.prototype=

newperson()

;student.prototype.constructor=student;

JS中的類與類的繼承

我們知道,js中沒有類或介面的概念,即不能直接定義抽象的類,也不能直接實現繼承。不過,為了程式設計的方便,我們可以在 js 中模擬類和繼承的行為。首先捋清楚類和物件的關係 類 比如人類,指的是乙個範圍 物件 比如某個人,指的是這個範圍中具體的物件js中的function作為建構函式時,就是乙個類,通...

Lua類建立與繼承

ctor name 2.self.name name 3.if self.name then 4.print 列印名字 self.name 5.end 6.self oncreate 7.end 8.方法oncreate 10.print 執行進來了 11.end 12.方法 initview 14...

js類的繼承

如何實現類的繼承呢?有如下2個建構函式 function peopleclass peopleclass.ptototype function studentclass name,function peopleclass peopleclass.ptototype function studentc...