js中常見繼承方式

2022-06-08 05:12:09 字數 2811 閱讀 4495

function father()

father.prototype.getvalue = function()

function son()

//繼承father

son.prototype = new father();//原型重寫,contructor被改寫

son.prototype.construtor = son;//重新指向son

son.prototype.getsonvalue = function()

var instance = new son();

console.log(instance.getvalue());

function father()

function son()

son.prototype = new father;

var instance1 = new son();

instance1.colors.push("black");

console.log(instance1.colors);

instance2 = new son();

instance2.colors.push("pink");

console.log(instance2.colors);

function father(name)

father.prototype.sayname = function()

function son(name,age)

son.prototype = new father();//使用原型鏈繼承超型別方法

son.prototype.constructor = son;//重新指向son

son.prototype.sayage = function()

var instance1 = new son("lisi",12);

instance1.colors.push("brown");

console.log(instance1.colors);

instance1.sayname();

instance1.sayage();

var instance2 = new son("hah",22);

instance2.colors.push("black");

console.log(instance2.colors);

instance2.sayname();

instance2.sayage();

var person = ;

var anotherperson = object.create(person);

anotherperson.friends.push("yixiu");

console.log(person.friends);

function createanother(original)

return clone;

}var person = ;

//缺點:無法進行函式復用,只能使用父類中的方法

// person.prototype.say = function()

var anotherperson = createanother(person);

anotherperson.friends.push("yixiu");

console.log(person.friends);

anotherperson.sayhi();

// anotherperson.say();

function extend(subclass,superclass);

f.prototype = superclass.prototype;

=superclass.prtotype相當於原型共享而非繼承

subclass.prototype = new f();//繼承superclass的原型

subclass.prototype.constructor = subclass;//原型重寫,手動繫結

subclass.superclass = superclass.prototype;//將superclass.prototype快取起來,方便後續訪問

if(superclass.prototype.constructor == object.prototype.constructor)

}function father(name)

father.prototype.sayname = function()

function son(name,age)

extend(son,father);//

son.prototype.constructor = son;//重新指向son

son.prototype.sayage = function()

var instance1 = new son("lisi",12);

instance1.colors.push("brown");

console.log(instance1.colors);

instance1.sayname();

instance1.sayage();

var instance2 = new son("hah",22);

instance2.colors.push("black");

console.log(instance2.colors);

instance2.sayname();

instance2.sayage();

JS常見的繼承方式

1.利用原型鏈prototype function person person.prototype.show function function man man.prototype new person var man new man man.show console.log man.name co...

js繼承常見的幾種方式

function parent parent.prototype.get function function son name son.prototype newparent var son1 newson 奧特曼 關鍵 把子類的原型指向父類的例項,從而繼承父類的私有屬性和原型屬性 優點 父類新增的...

js中常見的去重方式

幾種常用的去重的方式 var arr 2,6,1,15,11,7,12,8,5,4,3,12,10,1,7,2,4,4,4 12,false,false,3,3 去重方法1 先將陣列排序,然後迴圈陣列,判斷當前元素與上乙個是否相當,只針對number var unique1 function arr...