1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16/* 17 * @tc.name:bindfunction 18 * @tc.desc:test bind function 19 * @tc.type: FUNC 20 * @tc.require: issueI5NO8G 21 */ 22const module = { 23 x: 42, 24 getX: function() { 25 return this.x; 26 } 27}; 28 29const unboundGetX = module.getX; 30 31const boundGetX = unboundGetX.bind(module); 32print(boundGetX()); // expected output: 42 33 34function list() { 35 return Array.prototype.slice.call(arguments); 36} 37 38function addArguments(arg1, arg2) { 39 return arg1 + arg2; 40} 41 42const list1 = list(1, 2, 3); // [1, 2, 3] 43print(list1); 44 45const result1 = addArguments(1, 2); // 3 46print(result1); 47 48// Create a function with a preset leading argument 49const leadingThirtysevenList = list.bind(null, 37); 50 51// Create a function with a preset first argument. 52const addThirtySeven = addArguments.bind(null, 37); 53 54const list2 = leadingThirtysevenList(); // [37] 55print(list2); 56 57const list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] 58print(list3); 59 60const result2 = addThirtySeven(5); // 37 + 5 = 42 61print(result2); 62 63const result3 = addThirtySeven(5, 10); // 37 + 5 = 42, (the second argument is ignored) 64print(result3); 65 66// TestCase: builtins bind function. 67function foo(a, b) { 68 return a + b; 69} 70 71var bfoo = foo.bind(undefined, 1); 72bfoo(2); 73 74var array = [1]; 75array.forEach(bfoo); 76 77// TestCase: bind proxy 78const proxy = new Proxy(Array.prototype.includes, {}); 79const bind_proxy = proxy.bind(); 80print(bind_proxy.length) 81