Home > Web Front-end > JS Tutorial > Function introduction and usage examples of prototype keyword in JS_javascript skills

Function introduction and usage examples of prototype keyword in JS_javascript skills

WBOY
Release: 2016-05-16 17:28:09
Original
1107 people have browsed it

The prototype keyword can add methods or properties to original JS objects or classes created by yourself.
Inheritance can also be implemented.
Example:

Copy code The code is as follows:





Use of prototype keyword in JS

<script> <br><!-- In the original object in demo1 JS Add method --> <br>Number.prototype.add = function (num){ <br>return this num; <br>} <br>function but1_click(){ <br>alert((3).add( 8)); <br>} <br><!-- In the new object in demo2 JS, add attributes and methods--> <br>function Car(cColor,cWeight){ <br>this.cColor = cColor ; <br>this.cWeight = cWeight; <br>} <br>Car.prototype.drivers = new Array('zhangsan','lisi'); <br>Car.prototype.work = function (cLong){ <br>alert("I ran" cLong "km"); <br>} <br>function but2_click(){ <br>var c = new Car("red","5"); <br>c. drivers.push('zhaoliu'); <br>alert(c.drivers); <br>c.work(1); <br>} <br><!-- In the new object in demo3 JS, add attributes , the method is compactly written--> <br>function Rectangle(rWeight,rHeight){ <br>this.rWeight = rWeight; <br>this.rHeight = rHeight; <br>if( typeof this._init == ' undefined'){ <br>Rectangle.prototype.test = function (){ <br>alert("test"); <br>} <br>} <br>this._init = true; <br>} <br>function but3_click(){ <br>var t = new Rectangle(6,8); <br>t.test(); <br>} <br><!-- demo4 prototype inheritance--> <br>function objectA(){ <br>this.methodA = function (){ <br>alert("I am method A"); <br>} <br>} <br>function objectB(){ <br>this .methodB = function (){ <br>alert("I am method B"); <br>} <br>} <br>objectB.prototype = new objectA(); <br>function but4_click(){ <br>var t = new objectB(); <br>t.methodB(); <br>t.methodA(); <br>} <br></script>

< ;h2> Use of prototype keyword






< ;/body>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template