如何为该功能添加其他优惠

时间:2016-05-20 04:06:32

标签: javascript

我是一名Javascript学习者。我正在练习Javscript对象的属性和方法 我想向Black pen添加另一个优惠,假设它将是" 10%",我该怎么走得更远。请帮忙。
这是编写代码的正确方法吗?

vim

2 个答案:

答案 0 :(得分:1)

您可以修改pen2商品功能

pen2.offer = function(){ return parseInt(pen.prototype.offer()) + 10 +"%" ; }

答案 1 :(得分:1)

可能现在你已经得到了答案。这是探索原型的另一种方式

让我们假设 pen 固定式 项目。固定项目也可以是预订标尺比例等等。因此可以安全地假设固定可以是父对象

pen 标尺 book 等可以是静止的孩子。 &安培;子对象可以继承属性。在javascript中它是基于原型的继承。

    function Stationary(){
     //See there is no options provided here
    }
    // Adding showItem & offers method to Stationary prototype property
    Stationary.prototype.showItem = function(){
        console.log("You have choosen " +this.item +" with " +this.color + " having "+ this.size + " size "+". And its price is Rs." 
                        + this.price +" with "+this.offers(this.offer) +" offer");
    }

    Stationary.prototype.offers = function(offer){
      if(offer){
        return offer;   
      } 
      else{
        return "No offer";
      }
    }

   // Creating an object with some property
    var _p1Options ={
       item:"Pen",
       color:"Indigo",
       size:"Large",
       price:25,
       offer:'12%'
    }


    //Creating a function which will accept the options
    function Item (options){
        this.item = options.item || "default";
        this.color = options.color || "default";
        this.price = options.price || "default";
        this.size = options.size || "default";
        this.offer = options.offer || "default";
    }

    //Setting Item's prototype to Stationary's constructor
    // It will allow us to inherit all the properties
    Item.prototype = new Stationary();
    //Create a _p1 object with Item constructor
    var _p1 = new Item(_p1Options);
    //Item does not have showItem property,it will inherit from Stationary
    console.log(_p1.showItem());

所以要回答你的问题,你可以创建一个像_p1Options&分配您想要的属性值(包括商品),而不是硬编码返回值。

查看此jsfiddle了解更多