JavaScript mode--prototype mode

Source: Internet
Author: User

Gof authoritative explanation is that the prototype pattern is a pattern that creates multiple objects based on this object by cloning an object.

To implement this prototype pattern, you can use the method Object.create in ECMAScript 5 directly. It is not tight to create objects that extend out to specific objects, and you can add new properties.

var vehicle = {  function  () {    this. Model);  }}; var car = object.create (vehicle, {   "model": {    "Ford",     true   }}); Car.getmodel ()

Object.create The first parameter is the object to be expanded, and the two parameters are new properties. The detailed use method can be used to check MDN.

There is a problem traversing an enumerable property, and he iterates through all the elements in the prototype chain and needs to be filtered with object.hasownproperty.

Check the code below:

// only the property values in car are output.  for (var in car) {    if(Car.hasownproperty (name)) {        Console.log (Car[name])    }}

When Object.create is not supported, such as IE8, we press the above example to simulate the prototype mode

varVehicle ={getmodel:function() {Console.log ("The model of this vehicle is:" + This. Model); }};varCar = (function(){    functionF () { This. Model = "Ford"; } F.prototype=vehicle; varf =NewF (); returnF;}) () Car.getmodel (); //Ford

JavaScript mode--prototype mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.