0%

函数表现

1
2
3
4
5
6
7
8
9
10
11
12
13
function F1() {
this.name = "f1";
}

function F2() {
this.name = "F2";
return {};
}

console.log("1: ", new F1().name);
console.log("2: ", F1().name);
console.log("3: ", new F2().name);
console.log("4: ", F2().name);

运行结果 👇

1
2
3
4
5
6
7
1: f1

2: error: Uncaught TypeError: Cannot read property 'name' of undefined

3: undefined

4: undefined

引用 MDN 的一段话关于 new 操作符

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. The new keyword does the following things:

  1. Creates a blank, plain JavaScript object;
  2. Links (sets the constructor of) this object to another object;
  3. Passes the newly created object from Step 1 as the this context;
  4. Returns this if the function doesn’t return its own object.

new做了这 4 件事

  1. 创建一个空的简单 JavaScript 对象(即{})
  2. 链接该对象(即设置该对象的构造函数)到另一个对象
  3. 将步骤 1 新创建的对象作为 this 的上下文
  4. 如果该函数没有返回对象,则返回 this

函数执行默认返回 undefined
new构造函数默认返回this
指定返回值优先级最高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums: number[]): number {
// return Object.entries(nums.reduce((prev, v) => {
// Reflect.has(prev, v) ? prev[v]++ : Reflect.set(prev, v, 1)
// return prev
// }, {})).sort((a, b)=>b[1] - a[1])[0][0]
let count = 0;
let majority = nums[0];

for (let i = 0; i < nums.length; i++) {
if (count === 0) {
majority = nums[i];
}
if (majority === nums[i]) {
count++;
} else {
count--;
}
}
return majority;
};