10 front-end knowledge points per day: acrobatics

Personal blog is online. Welcome to visit and comment!
No Reason - wangchloe's Personal Blog

If you have any questions, please let me know immediately to amend the following contents, so as not to mislead more people.

  • toString() && valueOf()

  • JSON stringify & parse

  • +new Date()

  • Analysis of Array.prototype.slice.call(arguments, 0)

  • JS Bridge Establishes Communication between Native and H5

    • Hybrid Communication Principle

    • JS Bridge

Something very fragmentary that I usually encounter is just inserting into this chapter.

1. toString() && valueOf()

  • toString() converts a logical value to a string and returns the result.

  • valueOf() returns the original value of the Boolean object

From knowing

These two methods are usually invoked implicitly by JS to satisfy different operations.

In numerical operations, valueOf(), such as a+b, is called first.

In string operations, toString(), such as alert(c), is called first.

<script>
    // This example comes from the script house
    var bbb = {
        i: 10,
        toString: function() {
            console.log('toString');
            return this.i;
        },
        valueOf: function() {
            console.log('valueOf');
            return this.i;
        }
    }

    alert(bbb); // 10 toString
    alert(+bbb); // 10 valueOf
    alert('' + bbb); // 10 valueOf
    alert(String(bbb)); // 10 toString
    alert(Number(bbb)); // 10 valueOf
    alert(bbb == '10'); // true valueOf
    alert(bbb === '10'); // false
</script>
<script>
    console.log({
        valueOf: function() {
            return 20;
        }
    } * {
        valueOf: function() {
            return 30;
        }
    });     // 600
</script>

2. JSON stringify & parse

json2.js - Introduces a solution to the undefined problem of IE7 and JSON versions below.

  1. JSON.stringify(object); object - > string serializes object strings into standard JSON strings

eg: {a:1,b:2} -> "{"a":1,"b":2}"

  1. JSON.parse(str); String - > JSON object serializes strings into objects

{"name":"wangchloe","age":"22"} ->

{
    age: "22",
    name: "wangchloe",
    _proto: Object
}
<a href="https://www.baidu.com/" attr1='13'>baidu.com</a>
<script>
    var oA = document.querySelector('a');
    console.log(oA.getAttribute('attr1'));  // 13

    oA.setAttribute('attr1', '14');
    var num = oA.getAttribute('attr1');

    console.log(oA.getAttribute('attr1'));  // 14
    console.log(typeof number);  // String can only get string type by setting custom properties directly

    oA.setAttribute('attr1', JSON.stringify({name: 14}));

    var num2 = oA.getAttribute('attr1');

    console.log(num2);  // {"name": "14"}
    console.log(JSON.parse(num2));
    // Object {name: "14"}
    //     name: "14"
    //     -> _proto_: Object

    console.log(JSON.parse(num2).name);  // 14
    console.log(typeof JSON.parse(num2).name);  // number JSON transformation yields the true type
</script>

3. +new Date()

<script>
    s = new Date().toString();
    // "Wed May 17 2017 11:00:16 GMT+0800 (China Standard Time)"

    t = (+new Date()).toString();
    // "1494990039861"
    // + new Date(); equivalent to new Date().getTime(); abbreviated to get milliseconds
</script>

4. Array.prototype.slice.call(arguments, 0) analysis

Converting objects with length attributes to arrays

<script>
// Internal Implementation of array.js slice
function slice(start, end) {
    var len = ToUint32(this.length),
        result = [];
    for (var i = start; i < end; i++) {
        result.push(this[i]);
    }
    return result;
}
</script>
<script>
    // Pass in the arguments class array and call the Array.prototype.slice prototype method
    // And use call() method to limit the scope to arguments
    // Here Array.prototype can be understood as arguments
    // The parameter 0 is the first parameter of the slice() method, that is, the start position index, which returns the entire array.
    Array.prototype.slice.call(arguments, 0);
</script>

5. JS Bridge Establishes Communication between Native and H5

Hybrid Communication Principle

Background: In native APP development, there is a component of WebView (webview in Android, UIWebview below iOS 7, and WK Webview above 7), which can load Html files.

  • IOS

    • Object-C can call js directly, just call stringByEvaluating JavaScriptFromString, and get the return value of js directly.

    • js can't call Object-C directly. With shouldStartLoadWithRequest, it needs to intercept every url and do the corresponding local method to intercept the specified schema.

  • Android

    • Java can call js directly, but it can't get the return value of js directly.

    • After Java registers addJavascriptInterface, js can call Native's interface directly and get Native's return value. Make Java Closer to Javascript

    • Communication is achieved by shouldOverride Url Loading, or by intercepting all URL requests from the Web.

The following problems exist in basic communications

  • Under Android 4.2, addJavascriptInterface has security vulnerabilities

  • Under iOS 7, js cannot call Native

JS Bridge

  • url scheme interaction is a mature solution that can be perfectly compatible with various versions without the above problems.

Through JSBridge(JS and Native communication mechanism), H5 page can call Native's api,Native can also call the method of H5 page or notify H5 page callback.

Principle:
(1) Initialize the iframe of style.display=none created and set iframe.src as its own protocol. Every time a JS needs to communicate with Native, the JS side actively calls iframe.src. After Native receives the request notification, it invokes fetchQueue (visible source code) to get the message content; if Native needs to communicate with js, invoke JS directly and get the return value.

(2)

  • IOS
    js - > Native: js will send the message stored in the js side - > call iframe.src, trigger notification of Native - > Native interception request, call fetchQueue in js bridge and get the content of the returned message, process the message - > will need to return the data by calling js directly, let js process

  • Android
    JS - > Native: The return value of Js carried by shouldOverrideUrlLoading

(3) Native - > js: Native can call Js directly and get the returned content

<script>
function bridgeApp(protocol) {
    var iframe = document.createElement("iframe");
    var iframeStyle = document.createAttribute("style");
    var iframeSrc = document.createAttribute("src");

    iframeStyle.nodeValue = "display:none;width:0;height:0;";
    iframeSrc.nodeValue = protocol;
    iframe.setAttributeNode(iframeStyle);
    iframe.setAttributeNode(iframeSrc);
    document.body.appendChild(iframe);

    setTimeout(function() {
        document.body.removeChild(iframe);
    }, 250);
}
</script>

Five consecutive articles on Hybrid and JSBridge solutions

More content can be subscribed to my Wechat Public Number (without any reason), together to open the front-end small white advanced world!

When the public number does not send a message, push some front-end websites that I think are useful or see solutions to some problems. It is also more convenient for everyone to communicate, just sauce.

Keywords: Javascript JSON Android iOS Java

Added by twatkins on Fri, 28 Jun 2019 23:46:11 +0300