js物件導向程式設計

2021-07-16 07:47:37 字數 2046 閱讀 3532

js物件導向程式設計

js使用建構函式作為物件的模板.

var vehicle = function() ;

生成物件例項

var v = new vehicle();

v.price;//1000

傳引數的建構函式

var vehicle = function(value)

var v = new vehicle(500);

prototype物件

物件原型的作用,就是定義所有例項物件共享的屬性和方法.

constructor屬性

prototype物件有乙個constructor屬性,預設指向prototype物件所在的建構函式.

function p() {}

p.prototype.constructor === p //true

constructor分辨原型物件到底屬於哪個建構函式

function f() {};

var f = new f();

f.constructor === f; //true

f.constructor === regexp; //false

object.create()

用於從原型物件生成新的例項物件,可以替代new命令.

接收乙個物件作為引數,返回乙個新物件,後者完全繼承前者的屬性.

var a =

};var b = object.create(a);

b.print; //hello

b.print === a.print //true;

這串**等同於

var a = function() {};

a.prototype =

};var b = new a();

b.print === a.prototype.print;

object.create的重寫

if (typeof object.create !== 'function') ;

f.prototype = o;

return new f();}}

var o1 = object.create({});

var o2 = object.create(object.prototype);

var o3 = new object();

object.create(),可傳遞第二個引數,屬性描述物件,物件屬性,會新增到新物件.

var o = object.create({}, ,

p2:

});等同於

var o = object.create({});

o.p1 = 123;

o.p2 = 'abc';

in運算子和for...in迴圈

in運算子表示乙個物件是否具有某個屬性,不區分該屬性是繼承的還是自身的.

可以通過for...in...迴圈,獲取物件所有可以列舉的屬性

建構函式的繼承

要求,乙個建構函式繼承另乙個建構函式

兩步:子類建構函式中,呼叫父類的建構函式

function sub(value)

讓子類例項具有父類例項的屬性;

第二步,讓子類的原型指向父類的原型,這樣子類就可以繼承父類原型

sub.prototype = object.create(super.prototype);

另外一種方法

sub.prototype = new super();子類例項具有父類例項的方法.

例:function shape()

shape.prototype.move = function (x, y)

function rectangle()

rectangle.prototype = object.create(shape.prototype);

多重繼承

function m1()

function m2()

function s()

var s = new s();

s.hello; //hello

s.world; //world

JS物件導向程式設計 物件

一般面向過程的寫法都是寫很多function,壞處 1.復用不好 2.函式名稱容易重複衝突 下面介紹物件導向的寫法 在js中每個函式function都是乙個物件。比如,下面這個就是乙個物件,我們在使用的時候就可以當作物件來使用。function helloworld 使用下面測試函式 呼叫該函式就會...

js物件導向程式設計

1.直接建立物件 集中例項化問題 2.工廠模式 物件識別問題 3.建構函式模式 例項化物件的方法在每個例項上都要建立一遍 建構函式模式 function student name var student1 new student 張三 每個例項物件對應乙個引用,所以例項化物件時,所有屬性與方法都會重...

js,物件導向程式設計

工廠模式 function createperson name,age,job o.name name o.age age o.job job o.sayname function return o var tanya createperson tanya 30 female var ansel c...