JavaScriptCore你不知道的事

其实很长时间就想写一遍关于 JavaScriptCore文章,一是为了记录下自己的学习过程,二是讲下自己对学习JavaScriptCore的一些见解。

JavaScriptCore是在iOS7上才被Apple开放到ios application中的,让我们native的开发者有些事情可以做了。言归正传,让我们先从文档的 JavaScriptCore.h 头文件开始!

================
简单概述
================
// JavaScript运行环境的上下文
#import "JSContext.h" 

// 用于JavaScript类型和Objective-C类型的转换封装,JavaScript执行结果
#import "JSValue.h" 

// 处理JavaScript和Objective-C语言环境循环引用的问题
#import "JSManagedValue.h" 

// JavaScript执行环境的虚拟机,一个虚拟机代表一个线程的JavaScript运行环境
#import "JSVirtualMachine.h" 

// 是一个协议,只有遵守JSExport协议的Objective-C对象,才能被JavaScript调用
#import "JSExport.h" 

JSContext要点

  • 每一个JSContext初始化都带一个JSVirtualMachine,而 - (instancetype)init 时是系统提供了默认的JSVirtualMachine。
  • 使用 - (JSValue *)evaluateScript:withSourceURL:(NSURL *)sourceURL; sourceURL可以写一些debug代码在文件中,以方便调试代码用。
  • globalObject相当于浏览器中的window对象,实际上JavaScript代码都是在这个GlobalObject上执行的。
  • void(^exceptionHandler)(JSContext *context, JSValue *exception);可以重写实现,打印出我们要的exception信息,但别忘了把exception塞回给context. exception
  • 支持下标语法(SubscriptSupport)

JSValue要点

  • 每一个JSValue初始化都需要上下文创建!

  • JavaScript类型和Objective-C类型之间对应关系

    Objective-C type | JavaScript type
    --------------+----------------
    nil | undefined
    NSNull | null
    NSString | string
    NSNumber | number, boolean
    NSDictionary | Object object
    NSArray | Array object
    NSDate | Date object
    NSBlock | Function object
    id | Wrapper object
    Class | Constructor object

  • callWithArguments: 该方法用于 JSValue为 Function object时!

  • constructWithArguments:(NSArray *)arguments 调用JavaScript中的构造函数,arguments数组内容必须是JSValue对象,以供JavaScript能顺利转化

  • JSValue也支持下标语法

  • 支持结构体类型转换如:CGPoint,CGRect,CGSize,NSRange

向context中赋值block时要点(由于Objective-C block值捕获的特性)

  • 在向context中赋值block时,block不能直接访问外部变量和代码,应该通过参数传入。
  • block中利用JSContext提供的类方法,currentContext 、currentCallee、currentArguments 访问 content中的内容

JSManagedValue要点

该对象是用来解决JavaScrite语言环境和Objective-C语言环境不同而导致循环引用问题的。防止双方因内存释放问题而导致crash。

  • 初始化方法主要参数是 JSValue,相当于是对JSValue的包装,用于解决循环引用的问题。
  • JSManagedValue不是继承至JSValue

JSVirtualMachine要点

可以理解为一个JSVirtualMachine 虚拟机 就是一个单独JavaScrite运行环境,并且是线程安全的。前面提到了JSContent的初始化一定有一个对应的JSVirtualMachine运行环境,并且一个JSVirtualMachine可以创建多个JSContent,而且在层面是不同的JSContent是可以相互通信的。

不同JSVirtualMachine虚拟机环境将在不同的线程中,那也就是说我们实现类似Web worker的异步功能,但我们也别忘了线程之间的安全问题和线程之前的通信,也避免不了代码中使用很多的block回调。

JSExport要点

  • 是一个协议,不是一个对象

  • 平时编码的时候一般是自定义一个协议继承至JSExport,协议中可以声明属性、实例方法、类方法和初始化方法,使用时只要我们的Objective-C对象实现协议中声明的内容,将可以在被JavaScripte进行转换,反之,没有在JSExport中声明的将不能在JavaScript中访问。

  • 其实JSExport已经支持初始化方式的桥接 Google很多文章说 JSExport doesn't support constructors ,但在我的电脑环境为Xcode 8.3.1 IOS 10.3运行了下面的代码

      @protocol TestInterface <JSExport>
      -(instancetype)initWithString:(NSString *)string;
      @property (readonly) NSString *string;
      @end
      
      @interface TestClass : NSObject <TestInterface>
      @end
      
      @implementation TestClass
      @synthesize string = _string;
      - (instancetype)initWithString:(NSString *)string
      {
           if (!(self = [super init])) return nil;
          _string = [string copy];
          return self;
      }
      @end
      
      - (void)viewDidLoad {
          [super viewDidLoad];
          
          JSContext *context = [[JSContext alloc] init];
          context[@"TestClass"] = [TestClass class];
    
          JSValue *result0 = [context evaluateScript:@"(new TestClass())"];
          JSValue *result1 = [context evaluateScript:@"(new TestClass(\"Hello, world!\")).string"];
          JSValue *result2 = [context evaluateScript:@"(typeof TestClass.prototype.constructor)"];
          JSValue *result3 = [context evaluateScript:@"(new TestClass.prototype.constructor)"];
    
          NSLog(@"\n result0 : %@,\n result1:%@, \n result2:%@,  \n result3 = %@, \n class = %@",result0,result1,result2,result3,context[@"TestClass"]);
      }
    
      打印结果为:
      result0 : <TestClass: 0x608000013570>,
      result1:Hello, world!, 
      result2:function,  
      result3 = <TestClass: 0x608000013590>, 
      class = TestClass
    
  • constructor 可以调用JSExport中声明的类方法

      ===========
      swift代码
      ===========
      @objc protocol MovieJSExports: JSExport {
          var title: String { get set }
          var price: String { get set }
          var imageUrl: String { get set }
          // 声明的类方法
          static func movieWith(title: String, price: String, imageUrl: String) -> Movie
      }
      
      class Movie: NSObject, MovieJSExports {
          dynamic var title: String
          dynamic var price: String
          dynamic var imageUrl: String
    
          init(title: String, price: String, imageUrl: String) {
              self.title = title
              self.price = price
              self.imageUrl = imageUrl
          }
          
          // 类方法的实现,且通过传入的参数,初始化一个Movie对象
          class func movieWith(title: String, price: String, imageUrl: String) -> Movie {
              return Movie(title: title, price: price, imageUrl: imageUrl)
          }
      }
      
      ==============
      JavaScript代码
      ==============
      var mapToNative = function(movies) {
          return movies.map(function (movie) {
              // constructor 调用Movie实现的类方法,返回Movie对象,这个map用的精髓
              return Movie.movieWithTitlePriceImageUrl(movie.title, movie.price, movie.imageUrl);
          });
      };
    

以上代码出自:
JavaScriptCore Tutorial for iOS: Getting Started

JavaScript和Objective-C之间的相互调用

  • Objective-C调用JavaScript

      ===============
      通过JSContent
      ===============
      - (JSValue *)evaluateScript:(NSString *)script;
      - (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL NS_AVAILABLE(10_10, 8_0);
      
      ===============
      通过JSValue 
      ===============
      // 适用于JSValue 为 Functions
      - (JSValue *)callWithArguments:(NSArray *)arguments;
      // 适用于JSValue 为一个constructor    可以通过@"Class.prototype.constructor" 获得,上面有类是的代码
      - (JSValue *)constructWithArguments:(NSArray *)arguments;
      // 适用于JSValue中的声明的方法
      - (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;
    
  • JavaScript调用Objective-C

    一种方式是通过 block 的方式,把一个block塞入JSContent中,然后JavaScript就能调用对应的function了

    第二种方式是通过 JSExport中的声明,通过Objective-C实现,而JavaScript负责调用

Objective-C捕获JavaScript中的exception

通过exceptionHandler这个block 
context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
    context.exception = exception;
    NSLog(@"exception");
};

补充

  • 平时开发中可以把JavaScript代码写入对应的.js文件中,便于管理和执行JavaScript时通过文件的方式生成JavaScript代码
  • Objective-C也可以实现 JavaScript中的console,基本原理就是利用 + (NSArray *)currentArguments;方法
  • JSExportAs(PropertyName, Selector) 使用可以对比较长的Methods取一个适合JavaScript调用的名字

最后

写到这里的时候,才感觉到该文章偏理论了,后续如果有时间将提供一些相关代码。希望这边文章能对你理解JavaScriptCore有帮助,以上内容有什么问题可以提出,我将及时改正!一起学习、一起成长!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容