javascript object-oriented exercise answer

Posted by webbyboy on Sun, 01 Dec 2019 17:36:21 +0100

The second chapter

1. If we execute the following statements in the console, what are the results? Why?

var a; typeof a;   undefined
> var s = '1s'; s++;   NaN
> !!"false";   true
> !!undefined;   false
> typeof -Infinity;   number
> 10 % "0";    NaN
> undefined == null;    true
> false === "";     false
> typeof "2E+2";    string
> a = 3e+3; a++;    3000

2. What is the value of v after executing the following statement?

var v = v || 10; if V is set to 100, 0 and null respectively, what will be the result?

100, 10, 10

3. Write a script program to print multiplication table. Tip: use nested loops.

for (let i = 1; i < 10; i++) {
    for (let j = i; j < 10; j++) {
      console.log(i + '*' + j + '= '+ i*j);
    }
  }


The third chapter

1. Write a function to convert hexadecimal value to color. Take blue as an example, FF should be expressed in the form of RGB (0,0255). Then name the function getRGB() and test it with the following code. Tip: you can treat a string as an array, and the elements of this array are characters.

function getRGB(color) {
  let color1 = color.replace(/#/g, '');
  console.log(color1)
  let a = parseInt(color1.substring(0, 2), 16);
  let b = parseInt(color1.substring(2, 4), 16);
  let c = parseInt(color1.substring(4), 16);
  return 'rgb(' + a + ',' + b + ',' + c + ')';
}
 

Chapter IV answers

4. Customize a constructor function of MyString() when the String() constructor does not exist. Remember that because String () doesn't exist, you can't use any methods and properties that belong to the built-in String object when writing constructor functions. And make the object you create pass the following tests:

var s = new MyString("hello");
s.length;  //5

s[0];  //"h"

s.toString();  //"hello"

s.valueOf();  //"hello"

s.charAt(1);  //"e"

s.charAt("2");  //"l"

s.charAt("e");  //"h"

s.concat(" world!");  //"hello world!"

s.slice(1,3);  //"el"

s.slice(0,-1);  //"hell"

s.split("e");  //["h","llo"]

s.split("l");  //["he","","o"]

answer

function MyString(pstr){
    this.str=pstr.toString();
    this.length=this.str.length;

    for(var i=0;i<this.length;i++){
        this[i]=this.str[i];
    }

    this.toString=function (){
        return this.str;
    };

    this.valueOf=function (){
        return this.toString();
    };
    this.charAt=function(index){
        index=parseInt(index,10);
        index=isNaN(index)?0:index;
        return this[index];
    };
    this.concat=function(concatStr){
        return this.str+concatStr;
    };
    this.slice=function(startIndex,endIndex){
        while(startIndex<0){
            startIndex=startIndex+this.length;
        }
        while(endIndex<0){
            endIndex=endIndex+this.length;
        }
        if(endIndex<=startIndex){
            return "";
        }
        var resultStr="";
        for(var i=startIndex;i<endIndex;i++){
            resultStr+=this[i];
        }
        return resultStr;
    };
    this.split=function(s){
        var resultArr=[];
        var tempStr="";
        for(var i=0;i<this.length;i++){
            if(this[i]===s){
                resultArr.push(tempStr);
                tempStr="";
            }else{
                tempStr+=this[i];
            }
        }
        resultArr.push(tempStr);
        return resultArr;
    };
    this.reverse=function(){
        var tempArr=[];
        var i;
        for(i=0;i<this.length;i++){
            tempArr[i]=this[i];
        }
        tempArr.reverse();
        this.str=tempArr.join("");
        for(i=0;i<this.length;i++){
            this[i]=tempArr[i];
        }
    };
}

6. If the Array() constructor and the related array text identifier do not exist, customize a similar MyArray() constructor and make it pass the following tests:

var a = new MyArray(1,2,3,"test");
a.toString();
//"1,2,3,test"

a.length;
//4

a[a.length-1];
//"test"

a.push("boo");
//5

a.toString();
//"1,2,3,test,boo"

a.pop();
//boo

a.toString();
//"1,2,3,test"

a.join(",");
//"1,2,3,test"

a.join(" isn\'t");
//1 isn't 2 isn't 3 isn't test"

answer

function MyArray(){
        this.length=arguments.length;
        for(var i=0;i<this.length;i++){
            this[i]=arguments[i];
        }

        this.toString=function(){
            var resultStr="";
            for(var i=0;i<this.length;i++){
                if(i===this.length-1){
                    resultStr+=this[i].toString();
                }else{
                    resultStr+=this[i].toString()+",";
                }
            }
            return resultStr;
        };
        this.push=function(obj){
            this[this.length]=obj;
            this.length++;
            return this.length;
        };
        this.pop=function(){
            if(this.length===0){
                return null;
            }
            result=this[this.length-1];
            this[this.length-1]=undefined;
            this.length--;
            return result;
        };
        this.join=function(str){
            var resultStr="";
            for(var i=0;i<this.length;i++){
                if(i===this.length-1){
                    resultStr+=this[i].toString();
                }else{
                    resultStr+=this[i].toString()+str;
                }
            }
            return resultStr;
        }
    }

 

The seventh chapter

1

var win = window.open('http://www.baidu.com', 'packt', 'width=200,height=200,resizable=yes');
setTimeout(() => win.resizeTo(400, 400), 1000);

2

2.1

    function walkDOM(n, callback) {
      do {
        callback(n);
        if(n.hasChildNodes()) {
          walkDOM(n.lastChild, callback);
        }
      } while (n = n.previousSibling);
    }

    function callback(n) {
      console.log(n)
    }

    walkDOM(document.documentElement, callback);

2.2

function include(src) {
  var script = document.createElement('script');
  script.src = src;
  document.head.appendChild(script);
}
include('somescript.js');

3

let myevent = {
      addListener(element, event_name, callback) {
        if (element.length > 1) {
          for (let item of element) {
            addEvent(item, event_name, callback);
          }
        } else {
          addEvent(element, event_name, callback);
        }

        function addEvent(element, name, callback) {
          if (element.addEventListener) {
            element.addEventListener(event_name, callback, false);
          } else if (element.attachEvent) {
            element.attachEvent(event_name, callback, false);
          } else {
            element.event_name = callback;
          }
        }
      },
      removeListener(element, event_name, callback) {
        if (element.removeEventListener) {
          element.removeEventListener(event_name, callback, false);
        } else if (element.detachEvent) {
          element.detachEvent(event_name, callback, false);
        }
      },
      getEvent(event) {
        event = event || window.event;
        return event;
      },
      getTarget(event) {
        const target = event.target || event.srcElement;
        return target;
      },
      stopPropagation(event) {
        event.stopPropagation() || (event.cancelBubble = true);
      },
      preventDefault(event) {
        event.preventDefault() || (event.returnValue = false);
      }
    }

    function myCallback(e) {
      e = myevent.getEvent(e);
      alert(myevent.getTarget(e).href);
      myevent.stopPropagation(e);
      myevent.preventDefault(e);
    }

    myevent.addListener(document.links, 'click', myCallback);

4

let ajax = {
  request(url, method, callbak, params) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = (function (myxhr) {
      return function() {
        if (myxhr.readyState === 4 && myxhr.status === 200) {
          callbak(myxhr);
        }
      }
    })(xhr);
    xhr.open(method, url, true);
    xhr.send(params || '');
  }
}

function myCallback(xhr) {
  alert(xhr.responseText);
}
ajax.request('somefile.txt', 'get', myCallback);
ajax.request('script.php', 'post', myCallback, 'first=John&last=Smith');



 

Topics: Javascript PHP