js new到底做了什么?如何重写new?

new 构造函数()执行顺序

  1. 在堆中开辟对象内存空间, 记为obj
  2. 在obj 中添加__proto__属性并指向 构造函数.prototype
  3. 将构造函数中的this 指向obj
  4. 执行构造函数内语句
  5. 若构造函数中没有reutrn 或return this或基本类型(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若return 引用类型,则返回值为这个引用类型

仿写new的行为

function People(name, age, phone) {
  this.name = name;
  this.age = age;
  this.phone = phone;
  //若构造函数中`没有reutrn 或return this或基本类型`(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若`return 引用类型`,则返回值为这个引用类型
  // return null;//无影响
  // return {};//返回此对象
  // return function(){};//返回此函数
}

function _new(...args) {
  let constructor = args[0];//获取构造函数
  let obj = Object.create(constructor.prototype);//创建空对象,并将原型指向构造函数的原型
  let res = constructor.call(obj, ...args.slice(1));//call强行将this指向第一个参数
  if ((typeof res === 'object' || typeof res === 'function') && res != null) {
    return res;
  } else {
    return obj;
  }
}

let a = _new(People, 'aa', 20, 132456);
let na = new People('aa', 20, 132456);
console.log(a, na);
//运行结果
People { name: 'aa', age: 20, phone: 132456 }
People { name: 'aa', age: 20, phone: 132456 }

在使用libcef注入JS,要先好集成准备,确保编译环境的兼容性,理解libcef3的架构,准备好集成的依赖项,可能需要特定版本的编译器和工具链,了解其如何集成到应用程序中以及事件处理和渲染机制,还要配置额外的编译选项和链接库 [^1]。 可以创建libcef对象,如使用`CefRefPtr<SimpleApp> app(new SimpleApp);`或者`CefRefPtr<SimpleApp> app = new SimpleApp();`,其指针引用计数由`CefRefPtr`管理,通过调用`AddRef()`和`Release()`方法自动管理引用计数 [^3]。 在合适的头文件中添加并重写相关方法,例如在`simple_handler.h`文件中添加`OnBeforePopup`方法,在主frame中加载地址,可根据具体需求在其中加入注入JS的逻辑。以下是`OnBeforePopup`方法示例代码: ```cpp // 包含一个头文件 #include "include/wrapper/cef_helpers.h" ... //其它代码省略 // 新加的函数 // 默认返回的是 false,这里在主frame中加载地址,然后返回true virtual bool OnBeforePopup(CefRefPtr<CefBrowser> browser, //浏览器对象 CefRefPtr<CefFrame> frame, const CefString& target_url, //要打开的地址 const CefString& target_frame_name, WindowOpenDisposition target_disposition, bool user_gesture, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings, CefRefPtr<CefDictionaryValue>& extra_info, bool* no_javascript_access) { CEF_REQUIRE_UI_THREAD(); if (!target_url.empty()) { //获取浏览器对象中的 主frame对象,然后加载url browser->GetMainFrame()->LoadURL(target_url); return true; } return false; } ``` 在需要注入JS的地方,通过`CefFrame`对象的`ExecuteJavaScript`方法执行JS代码。示例代码如下: ```cpp CefRefPtr<CefFrame> frame = browser->GetMainFrame(); if (frame) { frame->ExecuteJavaScript("alert('This is an injected JavaScript!');", frame->GetURL(), 0); } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值