本篇记录有关prototype的定义,自订及新增methods的简单操作。
原型:prototype
在JS里面,原型也是一个物件,而每个原型的物件都有自己的属性、methods或称函式。
当原型的methods(函式)有新增时,同样继承使用该原型的物件,也会同时新增该函式。属性也同样继承,但是属性的值则可以自订。原型也可以去继承其他原型的属性及函式;从a物件去继承A原型物件,A原型物件再去继承B原型物件时,流程就是原型鍊。要看属性:a.A或是a.B;要看函式a.A()或是a.B()。reference type:
var a = [1, 2, 3]; console.log(a);
a.forEach(function (params) { console.log(params); //1,2,3 })
primary type:
图中的toUpperCase极为从String原型继承的method。
var a = 'a'; console.log(a.toUpperCase()); var b = new String('b'); console.log(b); console.log(b.toUpperCase());
b是物件型别,但是他依然是继承于String原型,所以String的method依然可以使用。
延伸应用:
var b = new String('baby'); console.log(b); String.prototype.lasttext = function (params) { return this[this.length - 1] } console.log(b.lasttext());
b就是物件,属性及原型如下图:
利用新增String原型的method一个属性lasttext,且值为一个函式;因为JS除了primary tpye都是物件,这边设计要取最后一个字,所以length - 1。
console.log(b.lasttext()):y。
自订原型:利用建构函式
自订原型的属性:
利用建构子将函式转为新物件并供后续使用。
function BluePrintDog(name, color, size) { this.name = name; this.color = color; this.size = size; } var DogA = new BluePrintDog('TOM', 'black', 'small'); console.log(DogA);
DogA从BluePrintDog建构式取得3个属性。
自订原型的methods(函式):
因为在JS函式也是物件,所以利用 BluePrintDog.prototype.eat的方式在BluePrintDog上的新增methods。prototype在函式上是属性。 function BluePrintDog(name, color, size) { this.name = name; this.color = color; this.size = size; } BluePrintDog.prototype.eat = function () { console.log('乖乖吃') } var DogA = new BluePrintDog('TOM', 'black', 'small'); console.log(DogA); DogA.eat();