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// print(unboundGetX()); // expected output: undefined 31 32const boundGetX = unboundGetX.bind(module); 33print(boundGetX()); // expected output: 42 34 35function list() { 36 return Array.prototype.slice.call(arguments); 37} 38 39function addArguments(arg1, arg2) { 40 return arg1 + arg2; 41} 42 43const list1 = list(1, 2, 3); // [1, 2, 3] 44print(list1); 45 46const result1 = addArguments(1, 2); // 3 47print(result1); 48 49// Create a function with a preset leading argument 50const leadingThirtysevenList = list.bind(null, 37); 51 52// Create a function with a preset first argument. 53const addThirtySeven = addArguments.bind(null, 37); 54 55const list2 = leadingThirtysevenList(); // [37] 56print(list2); 57 58const list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] 59print(list3); 60 61const result2 = addThirtySeven(5); // 37 + 5 = 42 62print(result2); 63 64const result3 = addThirtySeven(5, 10); // 37 + 5 = 42, (the second argument is ignored) 65print(result3); 66 67// TestCase: builtins bind function. 68function foo(a, b) { 69 return a + b; 70} 71 72var bfoo = foo.bind(undefined, 1); 73bfoo(2); 74 75var array = [1]; 76array.forEach(bfoo);